204. Count Primes
Asked at 14Amazon48Microsoft46Google46Bloomberg44Meta34Apple30tcs46SAP62Epic Systems59Accenture54Citadel47Nvidia39Uber30Goldman Sachs28
Problem
Return how many prime numbers are strictly less than n.
Example: 10 → 4 (2, 3, 5, 7)
Constraints: n ≤ 5·10⁶.
Sieve of Eratosthenes: for each prime p with p² < n, cross out p², p²+p, ….
Complexity: O(n log log n).
class Solution:
def countPrimes(self, n: int) -> int:
if n < 3:
return 0
is_p = bytearray([1]) * n
is_p[0] = is_p[1] = 0
for p in range(2, int(n ** 0.5) + 1):
if is_p[p]:
is_p[p * p::p] = bytearray(len(range(p * p, n, p)))
return sum(is_p)
assert Solution().countPrimes(10) == 4
assert Solution().countPrimes(0) == 0
assert Solution().countPrimes(100) == 25
class Solution {
public int countPrimes(int n) {
if (n < 3) return 0;
boolean[] composite = new boolean[n];
int count = 0;
for (int p = 2; p < n; p++) {
if (composite[p]) continue;
count++;
for (long q = (long) p * p; q < n; q += p) composite[(int) q] = true;
}
return count;
}
}
func countPrimes(n int) int {
if n < 3 {
return 0
}
composite := make([]bool, n) // sieve of Eratosthenes below n
count := 0
for p := 2; p < n; p++ {
if composite[p] {
continue
}
count++
for j := p * p; j < n; j += p {
composite[j] = true
}
}
return count
}