Count Primes
Pattern: Sieve
Count the primes strictly below n with the sieve of Eratosthenes: each number not crossed out when you reach it is prime, and you cross out its multiples starting from its square.
The problem
Return the number of prime numbers strictly less than n.
Think first
- Why is testing each number separately slow?
- What does crossing out multiples do?
- Where can crossing start?
Hints
Brute force, and why it fails
Trial division for every number below n: O(n √n).
The key insight
Crossing out multiples marks all composites in O(n log log n) total.
Dry run
n = 10. 2 is prime: cross 4, 6, 8. 3 is prime: cross 9.
Step 1 of 2
The plan
if n < 3: 0
composite = all false
for i from 2 below n: if not composite[i]: count++; cross i × i, i × i + i, ...
Complexity
- Time
O(n log log n)- Space
O(n)
The sieve.
Edge cases
- n = 0, 1 or 2: 0.
- n = 3: 1.
- Large n: 64-bit i × i.
I've built my logic, show the code
Java
class Solution {
public int countPrimes(int n) {
if (n < 3) return 0; // primes strictly below n
boolean[] composite = new boolean[n];
int count = 0;
for (int i = 2; i < n; i++) {
if (composite[i]) continue;
count++; // nothing smaller divides i: it is prime
for (long j = (long) i * i; j < n; j += i) composite[(int) j] = true; // smaller multiples were crossed already
}
return count;
}
}C++
class Solution {
public:
int countPrimes(int n) {
if (n < 3) return 0; // primes strictly below n
vector<bool> composite(n, false);
int count = 0;
for (int i = 2; i < n; i++) {
if (composite[i]) continue;
count++; // nothing smaller divides i: it is prime
for (long long j = 1LL * i * i; j < n; j += i) composite[j] = true; // smaller multiples were crossed already
}
return count;
}
};Python
class Solution:
def countPrimes(self, n: int) -> int:
if n < 3: # primes strictly below n
return 0
composite = [False] * n
count = 0
for i in range(2, n):
if not composite[i]:
count += 1 # nothing smaller divides i: it is prime
for j in range(i * i, n, i): # smaller multiples were crossed already
composite[j] = True
return countCommon mistakes
- Counting n itself.
- Overflow in i × i.