Sub topic 7
The Sieve of Eratosthenes, Step by Step
Trial division tests one number at a time. To list every prime up to a limit n, running it on each candidate repeats a lot of work: the same small divisors get tried over and over. The sieve of Eratosthenes turns the question around. It does not ask "does anything divide this number?" for each number. Instead, it takes each prime and marks all of its multiples as composite. Whatever is never marked is prime.
This chapter assumes you know what prime and composite numbers are, that every integer greater than 1 has a prime factorization (the fundamental theorem of arithmetic), and that a composite number n always has a factor no larger than √n. You should be comfortable reading Python with lists and loops.
The idea in one paragraph
Write down the integers from 2 to n. The smallest number not yet crossed out is 2, so 2 is prime. Cross out every other multiple of 2. The next uncrossed number is 3. No smaller prime divides it, so it is prime. Cross out its multiples. Keep going: each time you reach a number that is still uncrossed, it is prime, and you cross out its multiples. You can stop once the current number p satisfies p * p > n. At that point, every number still uncrossed is prime.
Why it is correct
Two facts carry the whole argument.
- Nothing prime ever gets crossed out. The sieve only crosses out numbers of the form
k * pwithk >= 2. Such a number haspas a proper divisor, so it is composite. A prime has no proper divisor greater than 1, so it never appears in a crossing-out pass. - Every composite up to
ngets crossed out. Take a compositec <= n. Its smallest prime factorqsatisfiesq * q <= c <= n, by the square-root bound from the previous chapter. Soqis reached before the outer loop stops. When the sieve reachesq, nothing has crossedqout, because by fact 1 primes are never crossed. The pass forqthen crosses out all multiples ofq, includingc.
The fundamental theorem of arithmetic guarantees that c has a smallest prime factor at all. Put together, after the loop ends the uncrossed numbers are exactly the primes in [2, n].
There is a third, quieter point. When the sieve reaches an uncrossed number p, how do we know p is prime? If p were composite, its smallest prime factor q would be less than p with q * q <= p <= n. The pass for q would already have crossed p out. So "uncrossed when reached" means "prime".
Walking through n = 30
Start with 2 through 30 all unmarked. The outer loop runs while p * p <= 30, so p takes the values 2, 3, 4, and 5. At p = 6, 36 > 30 and the loop stops.
| Pass | p | Status of p | Newly crossed out | Notes |
|---|---|---|---|---|
| 1 | 2 | prime | 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 | Removes every even number except 2 |
| 2 | 3 | prime | 9, 15, 21, 27 | 6, 12, 18, 24, 30 were already crossed by 2 |
| 3 | 4 | crossed | none | Skipped: its multiples are multiples of 2 |
| 4 | 5 | prime | 25 | 10, 15, 20, 30 were already crossed |
| stop | 6 | n/a | n/a | 6 × 6 = 36 > 30 |
The survivors are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29. Notice that 7, 11, 13, and the rest never ran a pass of their own. Every composite up to 30 has a prime factor of 5 or less, so those primes had nothing left to remove.
Notice also how little each later pass adds. The pass for 2 removes 14 numbers, the pass for 3 removes 4, and the pass for 5 removes 1. Most of the work in a pass goes into re-marking numbers that a smaller prime already removed. A later chapter turns that observation into the O(n log log n) running time.
A first implementation
The direct translation keeps a list is_prime indexed by the number itself, so is_prime[k] answers "is k still uncrossed?". The list has n + 1 entries so that index n exists.
def sieve_basic(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(2 * p, n + 1, p):
is_prime[m] = False
p += 1
return [i for i, flag in enumerate(is_prime) if flag]
print(sieve_basic(30)) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]Each line has a job:
if n < 2: return []handles the empty case. Without it,is_prime[1] = Falsefails with anIndexErrorwhennis 0.is_prime[0] = is_prime[1] = Falseencodes the definition: 0 and 1 are neither prime nor composite, so they must not end up in the output.while p * p <= nis the square-root stopping rule. Integer multiplication avoids the floating-point rounding thatp <= math.sqrt(n)can suffer for very largen.if is_prime[p]skips composite values ofp. Correctness does not depend on it, because crossing out multiples of 4 removes nothing new. Without it, though, the sieve does extra passes.range(2 * p, n + 1, p)steps through the multiples ofpand leavespitself alone.
Watching the passes
A traced version prints what each pass changes. It reproduces the table above.
def sieve_trace(n):
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
p = 2
while p * p <= n:
if is_prime[p]:
newly = [m for m in range(2 * p, n + 1, p) if is_prime[m]]
for m in newly:
is_prime[m] = False
print(f"p={p}: newly crossed {newly}")
else:
print(f"p={p}: already crossed, skip")
p += 1
print("primes:", [i for i, flag in enumerate(is_prime) if flag])
sieve_trace(30)Output:
p=2: newly crossed [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
p=3: newly crossed [9, 15, 21, 27]
p=4: already crossed, skip
p=5: newly crossed [25]
primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]Look at the first number each pass newly crosses: 4 for p = 2, 9 for p = 3, 25 for p = 5. Each one is p * p. That pattern is not a coincidence, and the next chapter explains it.
The standard form
The usual way to write the sieve starts each inner loop at p * p instead of 2 * p. Nothing else changes:
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]Checking your sieve against trial division
A sieve is easy to get subtly wrong. Bugs usually show up only at particular values such as perfect squares. A cheap safeguard is to compare it against a slow, obviously correct reference over many values of n.
def is_prime_td(n):
if n < 2:
return False
d = 2
while d * d <= n:
if n % d == 0:
return False
d += 1
return True
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]
for n in range(0, 500):
expected = [k for k in range(n + 1) if is_prime_td(k)]
assert sieve(n) == expected, n
print("sieve matches trial division for n = 0..499")Testing every n from 0 upward, not just one large limit, catches edge-case bugs. Those include the empty result for n < 2 and limits that land exactly on a prime or on a square.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| `[True] * n` instead of `n + 1` | `IndexError` on `is_prime[n]`, or `n` itself never reported | Allocate `n + 1` entries so index equals value |
| Forgetting to clear 0 and 1 | Output starts with `[0, 1, 2, ...]` | Set both to `False` before sieving |
| `while p * p < n` (strict) | Squares of primes survive: `sieve(25)` includes 25, `sieve(49)` includes 49 | Use `<=`; when `n = q * q` the pass for `q` is needed |
| Inner loop starting at `p` | Every prime crosses itself out; result is empty | Start at `2 * p` or `p * p` |
| `int(n ** 0.5)` as the bound for huge `n` | Float rounding can come out one short and miss a square | Use `p * p <= n` or `math.isqrt(n)` |
| Removing `if is_prime[p]` | Still correct, but runs useless passes for composite `p` | Keep the check |
Memory is the real limit
The sieve gives up memory to save time. It holds one flag for every integer up to n. A Python list of booleans uses about 8 bytes per entry for the pointers alone, so sieve(10**8) needs roughly 800 MB before it does any work. A bytearray cuts this to 1 byte per entry. Later chapters go further: odd-only and bit-packed layouts shrink the table, and a segmented sieve reaches far larger ranges with a small buffer. The algorithm described here stays the same in all of those versions. They change only how the flags are stored.
Exercise
A colleague writes the outer loop as while p * p < n. For which of these limits does their sieve return a wrong answer: n = 30, n = 49, n = 50? Explain why.
Show answer
Only n = 49. With the strict test, the loop stops before p = 7 because 7 7 = 49 is not less than 49. So 49 is never crossed out and is wrongly reported as prime. For n = 30 every composite has a prime factor of at most 5, and 5 5 = 25 < 30, so all of them are crossed. For n = 50, p = 7 runs because 49 < 50, so 49 is crossed.
Exercise
In sieve_basic(30), where the inner loop starts at 2 * p, how many times is the entry for 30 set to False, and by which values of p?
Show answer
Three times, by p = 2, p = 3, and p = 5. These are the three distinct prime factors of 30. The value p = 4 is skipped because it is already crossed out, and the loop stops before p = 6.
Exercise
What do sieve(0), sieve(1), and sieve(2) return, and which line of the implementation makes the first two work?
Show answer
sieve(0) and sieve(1) return [], and sieve(2) returns [2]. The guard if n < 2: return [] handles 0 and 1. Without it, is_prime[1] = False raises an IndexError for n = 0. For n = 2, the outer loop never runs because 2 * 2 > 2, so only index 2 stays True.
Exercise
Modify sieve_basic so it uses a bytearray instead of a list, and confirm it returns the same result for n = 100.
Show answer
Replace the list with is_prime = bytearray([1]) * (n + 1) and set is_prime[0] = is_prime[1] = 0. Inside the loop, assign is_prime[m] = 0. The final comprehension [i for i, flag in enumerate(is_prime) if flag] works unchanged, because 0 is falsy and 1 is truthy. Both versions return the 25 primes from 2 to 97.