Count Primes
Count Primes is LeetCode 204 (Medium). Given an integer n, return how many prime numbers are strictly less than n.
nitself is never counted, even when it is prime.ncan be 5 · 10⁶. Trial division of every number is too slow, and in Python the memory spent per number decides whether the sieve fits comfortably.
- 0 <= n <= 5 * 10⁶
Intuition
Run a sieve over the numbers 0 to n − 1 only. Mark every number as possibly prime; then each prime i crosses out i², i² + i, i² + 2i, …. Smaller multiples like 2i were already crossed out by a smaller prime factor.
The strict bound and the size limit shape the code:
- Size
n, notn + 1: the array never holds the numbern, so it cannot be counted by accident. - Stop once
i² ≥ n: such anihas no multiple left to cross out belown. - One byte per number: a Python
bytearrayof 5 · 10⁶ entries takes 5 MB, while a list ofTrue/Falsestores an 8-byte reference per slot, about 40 MB.
"How many primes below n" with n in the millions: one sieve, then count what survives. When only the count is needed, there is no reason to build a list of the primes.
Approach
Before reading on, decide how long the sieve array must be so that n is left out, and which i is the last one worth crossing out multiples for. Aim for O(n log log n) time.
Return 0 when n is below 3
The smallest prime is 2, and it only counts when n is at least 3. Returning early also avoids writing to index 1 of an array that has fewer than two slots.
Mark 0 and 1, keep the rest
Create bytearray([1]) * n and set indexes 0 and 1 to 0. Index j stands for the number j, and a 1 means no smaller prime has divided it yet.
Cross out multiples with one slice per prime
For each i from 2 while i * i < n, if sieve[i] is still 1, set the slice sieve[i*i::i] to zeros. One slice assignment writes every multiple in a single call, which is far faster than a Python loop over them.
Count the survivors
sum(sieve) adds up the 1s. A number below n is still marked only if no prime up to its square root divides it, so the sum is exactly the number of primes below n.
Code in Python, C++ and Java
Common pitfalls
Sizing the array for n + 1 numbers
sieve = bytearray([1]) * (n + 1)
sieve = bytearray([1]) * n
The extra slot is the number n, and when n is prime it survives the sieve and is counted. For n = 5 the answer is 2 (just 2 and 3), but the longer array returns 3.
Stopping the outer loop one number early
for i in range(2, int(n ** 0.5)):
for i in range(2, isqrt(n - 1) + 1):
range leaves out its end, so the last i with i * i < n is skipped. For n = 10 the loop stops after 2, 9 is never crossed out, and the answer is 5 instead of 4.
Clearing multiples one at a time in Python
for j in range(i * i, n, i):
sieve[j] = 0sieve[i * i :: i] = bytes(len(range(i * i, n, i)))
At n = 5 · 10⁶ the inner loop runs about 12 million Python steps in total. A single slice assignment per prime does the same writes inside C and ran about 20 times faster in our test at that size.
Complexity
p below √n crosses out about n / p numbers, and the sum of 1 / p over primes grows like log log n. The array is n bytes in Python, n bits with vector<bool> in C++, and n bytes as a Java boolean[].Count Primes FAQ
How is this different from the Sieve of Eratosthenes problem?
Sieve of Eratosthenes returns the list of primes up to and including n and explains the sieve itself in detail. Here the bound is strict, only the count is returned, and n is large enough that memory per number matters.
What if the question asks for the primes between L and R?
Sieve once up to R and build a running count pc[x] = number of primes ≤ x. Each range then costs one subtraction, pc[R] − pc[L − 1]. If R is too large to sieve whole but the range is short, a segmented sieve crosses out only the numbers from L to R using the primes up to √R.
Can the memory be cut further?
Yes. No even number above 2 is prime, so store odd numbers only: slot j stands for 2j + 1, and 2 is counted separately. That halves the array to 2.5 MB at the largest n. Packing 8 numbers per byte with a bit set cuts it by 8 again.