Sub topic 8
Starting Each Pass at p Squared
This chapter assumes you have read the step-by-step walkthrough of the sieve of Eratosthenes. You should also be comfortable with Python loops and range, with the idea that every composite number has a prime factor, and with the square root bound used in trial division. Here we look closely at one line of the sieve: the start of the inner loop. We ask why range(p * p, n + 1, p) is correct, what it saves, and where small mistakes around it cause real bugs.
The Line in Question
This is the sieve from the earlier chapter:
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]A first draft of the sieve would usually cross out 2p, 3p, 4p, .... The version above starts at p * p. It skips the multiples 2p, 3p, ..., (p-1)p. We need to show that skipping them never leaves a composite number unmarked.
Why the Skipped Multiples Are Already Crossed Out
Take a prime p and a skipped multiple k * p with 2 <= k < p.
kis at least 2, so it has some prime factorq.q <= k < p, soqis a prime smaller thanp.k * pis a multiple ofq, becauseqdividesk.- The sieve handled
qbeforep, since the outer loop counts upward.
One more check is needed. The pass for q also starts late, at q * q. So k * p only gets marked in that pass if it is at least q * q. It is: k * p >= q * p > q * q, because k >= q and p > q. So k * p lies inside the range the pass for q covered, and it was crossed out there.
The Loop Invariant
The same argument gives a statement that holds throughout the algorithm:
> When the outer loop reaches p, every composite number smaller than p * p has already been marked.
A composite c < p * p has a smallest prime factor q, and q * q <= c < p * p, so q < p. The pass for q started at q * q <= c and stepped by q, so it reached c.
This invariant does two jobs:
- It shows that the check
if is_prime[p]is reliable. Ifpwere composite, its smallest prime factorqwould satisfyq * q <= p < p * p, sopwould already be marked. Anypstill flagged when the loop reaches it is truly prime. - It explains why the outer loop can stop. Once
p * p > n, every composite up tonis smaller thanp * pand is already marked.
Two Optimizations That Are One Fact
Starting at p * p and stopping the outer loop at the square root of n are the same observation seen from two sides. Look at what happens for a prime p with p * p > n: range(p * p, n + 1, p) is empty. That pass would do nothing anyway. The while p * p <= n condition only avoids the cost of walking the outer loop through those empty passes.
Compare a sieve that starts each pass at 2 * p and never stops the outer loop early. Every prime up to n would get a pass, and a prime just above n / 2 would still write one useless mark. With the p * p start, the useless passes vanish because they are empty.
A Worked Example at n = 30
The table lists, for each prime p, the multiples that the 2p version would visit but the p * p version skips, and the smaller prime that had already marked each one.
| p | 2p version starts at | p² version starts at | Skipped multiples | Already marked by |
|---|---|---|---|---|
| 2 | 4 | 4 | none | n/a |
| 3 | 6 | 9 | 6 | 2 |
| 5 | 10 | 25 | 10, 15, 20 | 2, 3, 2 |
| 7 | 14 | 49 (pass is empty) | 14, 21, 28 | 2, 3, 2 |
For p = 2 nothing is saved, since 2 * 2 = 2 * p. For p = 7, 49 > 30, so the whole pass disappears. This is the square root bound showing up on its own.
Measuring the Savings
The script below counts array writes for both starting points and checks that the two versions return the same primes.
def sieve_count(n, start_at_square):
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
writes = 0
p = 2
while p * p <= n:
if is_prime[p]:
start = p * p if start_at_square else 2 * p
for m in range(start, n + 1, p):
is_prime[m] = False
writes += 1
p += 1
primes = [i for i, flag in enumerate(is_prime) if flag]
return primes, writes
for n in (100, 10_000, 1_000_000):
primes_a, writes_a = sieve_count(n, start_at_square=False)
primes_b, writes_b = sieve_count(n, start_at_square=True)
assert primes_a == primes_b
print(f"n={n:>9} start 2p: {writes_a:>9} start p*p: {writes_b:>9} saved: {writes_a - writes_b}")At n = 100 the counts are 113 writes against 104. Both versions here stop the outer loop at the square root, so this isolates the effect of the start point alone. Run the script to see the larger values.
Each prime p saves exactly p - 2 writes: the multiples 2p through (p-1)p. Summed over primes up to the square root of n, the savings grow roughly like n / ln n. The total work of the sieve grows like n log log n, which a later chapter covers. So the p * p start is a constant-factor gain. It does not change the asymptotic complexity. Its larger practical value is the one described above: it makes the square root stopping rule fall out naturally and keeps the code obviously correct.
Common Errors Around This Line
Starting at p Instead of p² or 2p
range(p, n + 1, p) crosses out p itself. Every prime then gets marked as composite, and the sieve returns an empty or nearly empty list. This bug is easy to write and easy to spot, since the output is obviously wrong.
Floating-Point Square Roots
Writing the outer bound as p <= int(n ** 0.5) works for small n but can be off by one for large n, because n ** 0.5 is a floating-point approximation. If the rounded value is too small, the last prime pass is skipped and a composite like q * q survives. Use the integer comparison p * p <= n, or math.isqrt(n), which is exact:
import math
n = 10**30 + 57
print(int(n ** 0.5), math.isqrt(n)) # the float version may differ from the exact valueOverflow in Fixed-Width Languages
Python integers never overflow. In C, C++, Java, or Go with 32-bit int, p * p overflows once p exceeds 46,340. A wrapped negative or small result can make p * p <= n true when it should be false, or start the inner loop at a garbage index. Use a 64-bit type for p * p, or write the condition as p <= n / p, which cannot overflow.
Off-by-One at the Top of the Range
range(p * p, n + 1, p) includes n. Writing range(p * p, n, p) leaves n unmarked when n is a multiple of p. For example, sieve(25) would then report 25 as prime, because 25 is only ever marked in the pass for 5 at index 25.
Forgetting p² When the Start Is Computed
In variants where the start index is not simply p * p, it is easy to lose the bound. The segmented sieve, covered in a later chapter, sieves a window [lo, hi]. There the start is the first multiple of p in the window, but never less than p * p:
lo, p = 2, 3
start = max(p * p, ((lo + p - 1) // p) * p)
print(start) # 9, not 3Without the max, a window that contains p would cross out p itself, which is the first error in this list again.
Odd-Only Sieves
If you store only odd numbers, the first useful multiple is still p * p, which is odd because p is odd. The step becomes 2 * p, because p * p + p is even and not stored. Keeping the p * p start while forgetting to double the step marks the wrong entries.
Summary of the Reasoning
- Any multiple
k * pwithk < phas a prime factorq < p, and the pass forqreached it becausek * p > q * q. - When the outer loop reaches
p, every composite belowp * pis already marked. That makesis_prime[p]reliable and justifies stopping at the square root. - The saving is
p - 2writes per prime: a constant-factor gain, not a change in big-O. - Most bugs come from the bound itself: float square roots, overflow, a missing
n + 1, or losing themax(p * p, ...)in derived variants.
Exercise
In the sieve for n = 50, list the multiples of 7 that the p² version does not cross out during the pass for 7, and name for each one the smaller prime that already marked it.
Show answer
The pass for 7 starts at 49, so it skips 14, 21, 28, 35, and 42. Already marked by: 14 by 2, 21 by 3, 28 by 2, 35 by 5, 42 by 2. The pass for 7 then marks only 49.
Exercise
A colleague changes the inner loop to range(p * p, n, p). For which values of n does sieve(n) now return a wrong answer, and what goes wrong?
Show answer
It fails whenever n is composite and n is not crossed out by any pass that reaches it, which happens when n is a multiple of some prime p ≤ sqrt(n). Every composite n has such a prime factor, so in practice every composite n is wrongly included as prime. For example, sieve(25) returns 25 and sieve(30) returns 30. Prime n are unaffected.
Exercise
Prove that if the outer loop reaches some p and is_prime[p] is still True, then p is prime.
Show answer
Suppose p were composite with smallest prime factor q. Then q q ≤ p, so q < p, and the pass for q ran earlier. That pass marks qq, qq + q, ..., and p is a multiple of q with p ≥ qq, so p was marked False. This contradicts is_prime[p] being True, so p is prime.
Exercise
In a Java sieve using int, the outer loop is written while (p * p <= n) with n = 2,000,000,000. Explain what can go wrong and give a fix.
Show answer
p p overflows int once p exceeds 46,340. The sum wraps to a negative or small value, so the condition can stay true after p passes sqrt(n), and the inner loop may start at a garbage index. Fix it by computing in long, as (long) p p <= n, or by writing the condition as p <= n / p.