Sub topic 7
The Sieve of Eratosthenes, Step by Step
This chapter assumes you know what a prime is, can read Python loops and lists, and have seen why a composite number n always has a factor no larger than its square root. Trial division tests one number at a time. When you need every prime up to some limit n, testing each number separately repeats a lot of work. The sieve of Eratosthenes removes that repetition. It finds composites by generating them, which avoids testing anything.
The Core Idea
Write down every integer from 2 to n. The smallest number not yet crossed out is prime. Cross out all of its multiples, because each of them has that prime as a factor. Then move to the next number that is still not crossed out. It must also be prime, because no smaller prime divides it. Repeat this until you have used every prime up to the square root of n.
Every composite number up to n has a prime factor no larger than its square root. That factor will have crossed it out. So once the pass loop stops, every number left standing is prime.
A Worked Example up to 30
Here is the sieve running with n = 30. Because the square root of 30 is about 5.48, only the passes for 2, 3, and 5 do any work.
| Pass | p | Newly crossed out | Note |
|---|---|---|---|
| 1 | 2 | 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 | every even number above 2 |
| 2 | 3 | 9, 15, 21, 27 | 6, 12, 18, 24, 30 were already gone |
| — | 4 | none | 4 is crossed out, so skip it |
| 3 | 5 | 25 | 10, 15, 20, 30 were already gone |
| — | 6 | stop | 6 × 6 = 36 > 30 |
The survivors are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29. The sieve never ran a pass for 7, 11, or any larger prime. Each of those survives because nothing smaller divides it.
The Implementation
def sieve(n):
if n < 2:
return []
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
p = 2
while p * p <= n:
if is_prime[p]:
for m in range(p * p, n + 1, p):
is_prime[m] = False
p += 1
return [i for i, flag in enumerate(is_prime) if flag]
print(sieve(30)) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]The list index stands for the number itself, so is_prime[k] answers "is k prime?" directly. That is why the list has n + 1 entries. The inner loop starts at p * p instead of 2 * p. Starting at 2 * p also gives correct results, but it repeats work, and the next chapter explains why the smaller multiples can be skipped.
Common Errors
- Allocating
nentries instead ofn + 1. Thenis_prime[n]raises anIndexError, ornitself is never considered. - Using
range(p * p, n, p). The stop value ofrangeis exclusive, sonis never crossed out. For example,sieve(25)would wrongly report 25 as prime. - Forgetting to mark 0 and 1. Both would show up in the output as "primes."
- Stopping the outer loop at
p < math.sqrt(n). Floating-point rounding and the strict comparison can skip the last needed prime. Whennis the square of a prime, such as 49, that prime never gets a pass. Use the integer testp * p <= n. - Collecting results from index 0 without the false flags. If you build the output with
range(n), you losenitself.
Exercise
Run sieve(50) by hand. Which values of p actually perform a crossing-out pass, and which composite is the only one crossed out during the pass for p = 7?
Show answer
Passes run for p = 2, 3, 5, and 7, because 7 × 7 = 49 ≤ 50 and 8 × 8 = 64 > 50. The values 4 and 6 are skipped because they are already crossed out. The pass for p = 7 starts at 49 and crosses out only 49, since 56 > 50.
Exercise
If you change the outer loop condition to p * p < n, what does sieve(49) return incorrectly?
Show answer
It includes 49 in the list of primes. The loop stops before p = 7 because 7 × 7 = 49 is not less than 49, so 49 is never crossed out.