Count Primes
Medium
Topics
Given an integer n, return the number of prime numbers strictly less than n.
Example 1
Input: n = 10 Output: 4
Example 2
Input: n = 0 Output: 0
Example 3
Input: n = 2 Output: 0
Constraints
- 0 <= n <= 5*10^6
Editorial — intuition, approach, complexity and pitfalls
Intuition
Testing each number for primality by trial division costs O(sqrt n) per candidate, so O(n sqrt n) overall. At n up to 5*10^6 that is far too slow.
The sieve of Eratosthenes inverts the work. Instead of asking "is k prime", it crosses off composites: take each prime and mark every multiple of it. Nothing is ever tested; numbers that survive the marking are prime by construction.
Two optimisations matter and both are in the code:
- Start marking at
i*i, not2*i. Any smaller multiple ofihas a factor belowiand was already crossed off when that smaller prime was processed. - Stop the outer loop at
i*i >= n. A composite belownmust have a factor at or below its square root, so every composite is caught by then.
The running time is O(n log log n), which is the sum of n/p over primes p — close enough to linear that the log log factor rarely matters in practice.
Approach
- A boolean array of size
n, all true; mark 0 and 1 false. - For each
iwhilei*i < n: ifiis still marked prime, cross offi*i, i*i+i, i*i+2i, ... - Count the survivors.
Dry Run
n = 20, counting primes strictly below 20
start [F,F,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T]
2 3 4 5 6 7 8 9 ...
i=2 prime, cross 4,6,8,10,12,14,16,18
i=3 prime, cross 9,15 (6 and 12 already gone)
i=4 i*i = 16 < 20 but 4 is already crossed, skip
i=5 i*i = 25 >= 20, loop ends
survivors 2,3,5,7,11,13,17,19 -> answer 8
note i=3 starts at 9, not 6: 6 was crossed by 2Complexity
- Time — O(n log log n): each prime
pperforms aboutn/pmarkings, and the sum over primes converges ton log log n. Against O(n sqrt n) for trial division. - Space — O(n): the boolean array. This is the trade the sieve makes — it buys speed with memory, and at
n = 5*10^6that is a few megabytes. A segmented sieve processes the range in blocks if the array will not fit, which is the answer if the bound grows.
Common Pitfalls
- Starting the inner loop at
2*i. Correct but wasteful — those multiples are already crossed off, and it changes the constant factor noticeably. - Looping the outer index to
nrather than stopping atsqrt(n). Also correct, also wasted work. - Forgetting that the count is of primes strictly below
n, so the array is sizednand indexnis never considered. - Not marking 0 and 1 as non-prime, which inflates the count by two.
- Marking multiples of composites. The
if sieve[i]guard skips them; without it the work is repeated but the answer is unchanged.
Full Solution — all languages
class Solution:
def countPrimes(self, n):
if n < 3:
return 0
sieve = [True] * n
sieve[0] = sieve[1] = False
i = 2
while i * i < n:
if sieve[i]:
for j in range(i * i, n, i):
sieve[j] = False
i += 1
return sum(sieve)import java.util.*;
class Solution {
public int countPrimes(int n) {
if (n < 3) return 0;
boolean[] comp = new boolean[n];
int count = 0;
for (int i = 2; i < n; i++) {
if (!comp[i]) {
count++;
for (long j = (long) i * i; j < n; j += i) comp[(int) j] = true;
}
}
return count;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int countPrimes(int n) {
if (n < 3) return 0;
vector<bool> comp(n, false);
int count = 0;
for (int i = 2; i < n; i++) {
if (!comp[i]) {
count++;
for (long long j = (long long) i * i; j < n; j += i) comp[j] = true;
}
}
return count;
}
};/**
* @param {number} n
* @return {number}
*/ var countPrimes = function(n) {
if (n < 3) return 0;
const comp = new Array(n).fill(false);
let count = 0;
for (let i = 2; i < n; i++) {
if (!comp[i]) {
count++;
for (let j = i * i; j < n; j += i) comp[j] = true;
}
}
return count;
};