LeetCode #204 Medium

Count Primes

Count Primes is LeetCode 204 (Medium). Given an integer n, return how many prime numbers are strictly less than n.

  • n itself is never counted, even when it is prime.
  • n can 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.
Constraints
  • 0 <= n <= 5 * 10⁶
mathsievearray
Open on LeetCode ↗
02

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, not n + 1: the array never holds the number n, so it cannot be counted by accident.
  • Stop once i² ≥ n: such an i has no multiple left to cross out below n.
  • One byte per number: a Python bytearray of 5 · 10⁶ entries takes 5 MB, while a list of True/False stores an 8-byte reference per slot, about 40 MB.
How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1from math import isqrt
▶2 
▶3 
▶4class Solution:
▶5 def countPrimes(self, n: int) -> int:
▶6 if n < 3:
▶7 return 0
▶8 sieve = bytearray([1]) * n
▶9 sieve[0] = sieve[1] = 0
▶10 for i in range(2, isqrt(n - 1) + 1):
▶11 if sieve[i]:
▶12 sieve[i * i :: i] = bytes(len(range(i * i, n, i)))
▶13 return sum(sieve)
sieve: 1 byte per number10111213141516171819110n1111bytes11 bytes for 0 to 10, all set to 1
n11
array size11bytes
The array has exactly 11 slots, for the numbers 0 to 10. The dashed slot is 11 itself: it has no byte, so it can never be counted, even though 11 is prime.
sieve: 1 byte per number00011213141516171819110n119still 10 and 1 are not prime → set to 0
sieve[0]0
sieve[1]0
A prime must be greater than 1, so 0 and 1 are cleared by hand. Every other number keeps its 1 until a prime factor crosses it out.
sieve: 1 byte per number000112i13041506170819010n112prime i→4first multiple→4multiples set to 02 is prime → clear 4, 6, … up to 10
i2
slicefrom 4 step 2
One slice assignment zeroes every multiple of 2 from 4 on. For 2 that first multiple is 4, so every even number above 2 is cleared.
sieve: 1 byte per number00011213i041506170809010n113prime i→9first multiple→1multiples set to 03 is prime → clear 9, 12, … up to 10
i3
slicefrom 9 step 3
One slice assignment zeroes every multiple of 3 from 9 on. Smaller multiples such as 6 have a smaller factor and were handled earlier.
sieve: 1 byte per number0001121304i1506170809010n114next i→16i × i≥11nnext i is 4: 16 is not below 11 → stop
i4
i × i16
The first multiple 4 would clear is 16, which is past the end of the array. Any composite below 11 has a factor no bigger than 3, so it is already 0.
sieve: 1 byte per number00011213041506170809010n114primes below 11sum of the bytes → 4 primes
answer4
The bytes still set to 1 are the primes: 2, 3, 5, 7. Adding the bytes gives 4. 11 is prime too, but it sits outside the array.
05

Common pitfalls

Sizing the array for n + 1 numbers

✗ Wrong
sieve = bytearray([1]) * (n + 1)
✓ Right
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

✗ Wrong
for i in range(2, int(n ** 0.5)):
✓ Right
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

✗ Wrong
for j in range(i * i, n, i):
    sieve[j] = 0
✓ Right
sieve[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.

06

Complexity

Time
O(n log log n)
Space
O(n)
Each prime 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[].
07

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.