The sieve of Eratosthenes
1 One prime check at a time is too slow
An earlier lesson checked whether one number is prime in O(√n). Some problems ask about many numbers at once. Count Primes asks how many primes lie below n, for n up to 5 × 10⁶. Prime Factorisation asks for the prime factors of 10⁵ numbers.
Checking every number from 2 to n on its own costs up to √n steps each, so O(n√n) in all. At n = 5 × 10⁶ that is around 10¹⁰ steps. At about 10⁸ steps a second, it gets Time Limit Exceeded (TLE).
The sieve of Eratosthenes finds every prime up to n together, in a little more than n steps. It never divides anything. It only crosses numbers out.
2 Crossing out multiples
We write down every number from 0 to n. 0 and 1 are not prime, so they are out from the start. Every other number starts as "might be prime".
Then we repeat one step. We take the smallest number p that is not crossed out yet. If p had a smaller prime factor, that prime would have crossed p out already. So p is prime. Then we cross out the multiples of p, because p divides each of them.
Here it is for n = 49. The blue boxes are the primes found so far. The orange boxes are the numbers crossed out in that step.
A number that is not prime gets crossed out by its prime factors. The 15 numbers that survive have no smaller prime factor, so they are exactly the primes up to 49.
3 Start at p × p, stop once p × p passes n
The steps above did two things that need a reason. Each prime started crossing at p × p, not at 2p. And the sieve stopped at 8, long before 49.
- Start at p × p. A multiple below p × p is k × p with k smaller than p. Then k has a prime factor smaller than p, and that prime crossed the number out already. For p = 5, the multiples 10, 15 and 20 are 5 × 2, 5 × 3 and 5 × 4, and 2 and 3 crossed them out. The first multiple that needs 5 is 25.
- Stop once p × p passes n. The divisors lesson showed that a number that is not prime has a divisor no larger than its square root. Its smallest such divisor is a prime. So every number up to n that is not prime has a prime factor no larger than √n. Once p × p is past n, all those primes have had their turn.
The trace for n = 49:
p | isPrime[p] | first m | newly crossed out |
|---|---|---|---|
| 2 | true | 4 | 4, 6, 8, …, 48 |
| 3 | true | 9 | 9, 15, 21, 27, 33, 39, 45 |
| 4 | false | — | skipped |
| 5 | true | 25 | 25, 35 |
| 6 | false | — | skipped |
| 7 | true | 49 | 49 |
| 8 | stop, as 64 > 49 |
The outer loop only runs up to 7. The primes above 7, such as 47, never need a turn of their own. They are what is left after the crossing.
4 The code
The code keeps one true or false per number in isPrime. It sets 2 to n to true, crosses out as in the trace, and returns the array. A count of the primes, or a list of them, is one more pass over it.
C++
One bit per number. A vector<bool> packs eight values into a byte, so 10⁷ numbers take about 1 MB.
The inner loop is the slow part. For n in the millions, one slice assignment crosses out all of p's multiples at once and runs a few times faster: is_prime[p * p :: p] = [False] * len(range(p * p, n + 1, p)).
For n = 49 the array is true at 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 and 47. For n = 0 or 1 it holds no true at all.
5 What it costs
The prime p crosses out about n / p numbers. So the total work is about n/2 + n/3 + n/5 + n/7 + …, with one term for each prime up to √n.
Some numbers are crossed out more than once. 12 is crossed out by 2 and again by 3. Still, the sum 1/2 + 1/3 + 1/5 + 1/7 + … grows very slowly, like log log n, and it stays under 3 even at n = 10⁷. So the time is O(n log log n), close to linear.
At n = 10⁷, the sieve crosses out around 2 × 10⁷ times. Checking each number up to its square root can take around 3 × 10¹⁰ steps.
The array holds n + 1 entries, so the space is O(n). At one byte each, n = 10⁷ takes about 10 MB, which is fine. At n = 10⁹ it would need 1 GB. So a sieve suits limits up to about 10⁷.
6 Smallest prime factors, for factorising
Prime Factorisation gives up to 10⁵ numbers, each up to 10⁶. Dividing each one by every number up to its square root takes about 10³ steps per number, so around 10⁸ in all. That is right at the limit.
The sieve does better with one change. Instead of true or false, it stores each number's smallest prime factor, or spf. When the prime p reaches m, it sets spf[m] = p only if no prime set it before. The primes arrive in increasing order, so the first one to arrive is the smallest. Each prime sets spf[p] = p for itself.
Starting at p × p is still safe. A number m that is not prime has a smallest prime factor q with q × q no larger than m, so q's turn reaches m.
Then factorising x is a short loop. spf[x] is a prime factor of x, so we write it down and divide x by it. We repeat on what is left until x is 1.
Each division at least halves x, so a number up to 10⁶ takes at most 20 steps. For 10⁵ numbers that is about 2 × 10⁶ steps, after one sieve.
This time the outer loop runs all the way to n, so that every prime above √n also sets its own spf[p].
C++
start is a long long. p now goes up to n, and from p = 46,349 on, p × p is past the int range.
start is a long. p now goes up to n, and from p = 46,349 on, p × p is past the int range.
start is a long. p now goes up to n, and from p = 46,349 on, p × p is past the int range.
No overflow. Go's int is 64 bits, so p × p fits for any n we can store an array for.
No overflow. usize is 64 bits, so p × p fits for any n we can store an array for.
The code gives 2, 3, 3 for 18 and 3, 3, 5 for 45. For 1 it gives an empty list, because the loop never runs.
7 Mistakes and their inputs
Each of these passes some examples and fails on one input.
- An array of size n. For "primes up to n", index n must exist, so the array needs n + 1 entries. With 49 entries, the sieve for n = 49 writes to index 49 and gets Runtime Error. Count Primes counts primes strictly below n, so read which one the problem asks for.
- 0 and 1 left as true. No pass ever crosses them out, since every pass starts at p × p. The count for n = 49 then comes out 17 instead of 15.
p * p < ninstead of<=. For n = 49, the loop stops before 7, so 49 is never crossed out and counts as a prime.- p × p in 32 bits in the spf sieve. With n = 10⁶, p = 46,349 makes p × p wrap to a negative number.
spf[m]then reads outside the array, and the code gets Runtime Error. - Starting at 2p. This one is not a bug. The answer is the same, because the extra steps only cross out numbers that are already crossed out. It is a little slower.
8 When to use it
The signal is that we need primes or prime factors for many numbers, and the largest of them is small enough for an array, up to about 10⁷.
- Is each of many numbers prime? One sieve up to the largest, then each answer is one array read.
- How many primes in many ranges? After the sieve, a running count of primes up to each number answers any range with one subtraction. The prefix sums lesson builds that running count.
- Factorise many numbers. The spf sieve, then the divide loop for each number.
For one number, or for a number too large for an array, the O(√n) check from the divisors lesson is still the tool.
The habit to keep: when a problem asks about primes for many numbers, look at the largest value first. Up to about 10⁷, build one sieve and answer every question from the array.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.