Count Primes (LeetCode 204): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- If
n < 2, return 0, since there are no primes below 2. - Create
is_primeof lengthnfilled with True, then mark indices 0 and 1 as False. - Loop
ifrom 2 up toint(n ** 0.5). - If
is_prime[i]is still True,iis prime, so mark every multiple fromi * iup ton - 1, stepping byi, as False. - Return
sum(is_prime), which counts the entries still marked True.
Step-by-step example
n = 10
is_primecovers 0 through 9, with 0 and 1 set to False. The outer loop runs fori= 2 and 3, sinceint(10 ** 0.5)is 3.i = 2is prime, so 4, 6 and 8 are marked False.i = 3is prime, so marking starts at 9, which is marked False. 6 was already handled by 2.- 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)1class Solution {
2 public int countPrimes(int n) {
3 if (n < 2) return 0;
4
5 boolean[] isPrime = new boolean[n];
6 Arrays.fill(isPrime, true);
7 isPrime[0] = isPrime[1] = false;
8
9 for (int i = 2; i * i < n; i++) {
10 if (isPrime[i]) {
11 for (int j = i * i; j < n; j += i) {
12 isPrime[j] = false;
13 }
14 }
15 }
16
17 int count = 0;
18 for (boolean p : isPrime) if (p) count++;
19 return count;
20 }
21}1class Solution {
2public:
3 int countPrimes(int n) {
4 if (n < 2) return 0;
5
6 vector<bool> isPrime(n, true);
7 isPrime[0] = isPrime[1] = false;
8
9 for (int i = 2; i * i < n; i++) {
10 if (isPrime[i]) {
11 for (int j = i * i; j < n; j += i) {
12 isPrime[j] = false;
13 }
14 }
15 }
16
17 return count(isPrime.begin(), isPrime.end(), true);
18 }
19};Time and space complexity
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.
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 thann, so the array has lengthn, notn + 1. - Starting the inner loop at
2 * iinstead ofi * i. It is still correct but does redundant work on multiples already crossed out. - Looping the outer index to
ninstead of √n. That is correct too, but every iteration past √n does nothing useful. - Forgetting to handle
nof 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.