11.7 Count Primes
11.7.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 204
- Difficulty: Easy
- URL: https://leetcode.com/problems/lc-count-primes/
- Tags:
- Techniques: Dynamic Programming, Tabulation, Math, Sieve
11.7.5 Solution - Sieve of Eratosthenes
11.7.5.1 Walkthrough
Maintain a boolean array marking composite numbers. Starting from 2, whenever a number is unmarked (prime), mark all multiples starting at i * i as composite. Count the primes that remain unmarked below n.
11.7.5.3 Implementation Steps
- If
n < 2, return0. - Create boolean
isComposite[n]. - For each
iup tosqrt(n), if not composite, mark multiplesi * i, i * i + i, .... - Count indexes with value
false(primes).
11.7.5.4 Code - Java
public int countPrimes(int n) {
if (n < 2) {
return 0;
}
boolean[] composite = new boolean[n];
for (int i = 2; i * i < n; i++) {
if (!composite[i]) {
for (int j = i * i; j < n; j += i) {
composite[j] = true;
}
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (!composite[i]) {
count++;
}
}
return count;
}