Count Primes (LeetCode 204): Solution and Explanation

Medium
Array
Math
Enumeration
Number Theory

Given an integer n, count how many prime numbers are strictly less than n. A prime is a whole number greater than 1 whose only divisors are 1 and itself.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force tests each number below n for primality by trying divisors up to its square root. That costs O(√k) per number and O(n√n) overall, which is far too slow for n up to five million.

The sieve flips the work around. Instead of asking whether each number has a divisor, you start with every number marked as possibly prime and cross out the multiples of each prime you find. When you reach a number that has not been crossed out, nothing smaller divides it, so it is prime, and its multiples can be crossed out in turn. Each composite gets eliminated by its prime factors without any division at all.

Two observations keep the sieve tight. First, for a prime i you can start crossing out at i * i, because any smaller multiple i * k with k < i was already crossed out when you processed the smaller factor k. Second, you only need to sieve with i up to √n: if a number below n is composite, it has a factor no larger than √n, so it is crossed out by then. After the sieve, the primes are simply the entries still marked true.

The memory cost is the trade you make for speed. A five million entry boolean list is easily affordable, and in exchange each composite is crossed out by a cheap array write instead of a division test. If memory were tight, a segmented sieve processes the range in blocks while keeping only the small primes up to √n in memory.

Approach: Sieve of Eratosthenes

  1. If n < 2, return 0, since there are no primes below 2.
  2. Create is_prime of length n filled with True, then mark indices 0 and 1 as False.
  3. Loop i from 2 up to int(n ** 0.5).
  4. If is_prime[i] is still True, i is prime, so mark every multiple from i * i up to n - 1, stepping by i, as False.
  5. Return sum(is_prime), which counts the entries still marked True.

Step-by-step example

n = 10
  1. is_prime covers 0 through 9, with 0 and 1 set to False. The outer loop runs for i = 2 and 3, since int(10 ** 0.5) is 3.
  2. i = 2 is prime, so 4, 6 and 8 are marked False.
  3. i = 3 is prime, so marking starts at 9, which is marked False. 6 was already handled by 2.
  4. The entries still True are 2, 3, 5 and 7, so the function returns 4.

Code: Python, Java, C++

1class Solution:
2    def countPrimes(self, n: int) -> int:
3        if n < 2:
4            return 0
5
6        is_prime = [True] * n
7        is_prime[0] = is_prime[1] = False
8
9        for i in range(2, int(n ** 0.5) + 1):
10            if is_prime[i]:
11                for j in range(i * i, n, i):
12                    is_prime[j] = False
13
14        return sum(is_prime)

Time and space complexity

Time

O(n log log n)

Each prime p up to √n crosses out about n / p multiples. Summing n / p over the primes gives n times the sum of prime reciprocals, which grows like log log n.

Space

O(n)

The boolean array has one entry for each number below n.

Other approaches

Trial division (time O(n√n), space O(1))

For each number below n, test divisors from 2 up to its square root. It needs no extra memory but is much slower for large n.

Linear sieve (time O(n), space O(n))

Keep a list of primes and cross out each composite exactly once by its smallest prime factor. It is truly linear, though in practice the classic sieve is usually just as fast.

Common mistakes

  • Counting primes up to and including n. The problem asks for primes strictly less than n, so the array has length n, not n + 1.
  • Starting the inner loop at 2 * i instead of i * i. It is still correct but does redundant work on multiples already crossed out.
  • Looping the outer index to n instead of √n. That is correct too, but every iteration past √n does nothing useful.
  • Forgetting to handle n of 0 or 1. Without the early return, is_prime[1] would index past a list of length 0 or 1.

Frequently asked questions

Why does the sieve start crossing out at i squared?

Every smaller multiple of i has a factor smaller than i and was already crossed out when that factor was processed. Starting at i * i skips that redundant work without missing anything.

Why is the Sieve of Eratosthenes O(n log log n)?

Each prime p crosses out about n / p numbers, and the sum of 1 / p over primes up to n grows like log log n. Multiplying by n gives the bound, which is nearly linear in practice.

How much memory does Count Primes need?

One boolean per number below n, so O(n). For five million entries that is a few megabytes, and a bytearray or bitset can shrink it further.

Is 1 a prime number?

No. A prime must have exactly two distinct divisors, and 1 has only one, so the sieve marks both 0 and 1 as not prime before it starts.