Sub topic 2
Why You Only Need to Check Up to the Square Root
This chapter assumes you can read Python loops and lists, know the modulo operator %, and recall that a prime has exactly two divisors: 1 and itself.
The Square Root Bound
Suppose n is composite, so n = a * b with 1 < a ≤ b < n. If a were larger than √n, then b ≥ a > √n too, and a * b > n. That contradicts n = a * b. So every composite n has a factor no larger than √n.
This means a primality test can stop once d * d > n. For n = 1,000,003, that is about 1,000 checks instead of a million. Writing the test as d * d <= n avoids floating-point square roots, which can round wrong for large integers.
The Sieve of Eratosthenes, Step by Step
Testing each number on its own repeats work. The sieve finds every prime up to n in a single pass:
- Write the numbers 2 through
nand mark them all as possible primes. - Take the smallest unmarked number
p. It is prime. - Cross out every multiple of
p. - Repeat with the next unmarked number until
p * p > n. Whatever is still unmarked is prime.
The square root bound tells you when to stop. Any composite m ≤ n has a prime factor no larger than √m, which is at most √n, so some earlier pass has already crossed m out.
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]Starting Each Pass at p Squared
Take any multiple k * p with k < p. It has a prime factor smaller than p, so an earlier pass has already crossed it out. The first multiple that still needs crossing out is p * p. For p = 7 and n = 30, the multiples 14, 21, and 28 are already gone, and 49 is larger than 30, so the pass does nothing.
Exercise
When sieving up to n = 50, which values of p run a crossing-out pass, and what is the first number each pass crosses out?
Show answer
The loop runs while p * p <= 50, so p goes up to 7. The passes that run are for the primes 2, 3, 5, and 7. They start at 4, 9, 25, and 49.