Sub topic 12
Sieving Large Ranges with a Segmented Sieve
This chapter assumes you already know the basic sieve of Eratosthenes, why each crossing-out pass starts at p squared, and why the plain sieve uses O(n) memory. It also assumes you can read Python with loops and integer division.
The Problem with One Big Array
The plain sieve allocates one flag for every number from 0 to n. Suppose you want the primes between 10^12 and 10^12 + 10^6. A plain sieve would need a trillion flags, even though you only care about a million of them. The time is wasted too, because the sieve marks numbers far below the range you want.
A segmented sieve fixes both problems. It splits the work into two parts:
- Find the base primes, which are all primes up to the square root of
hi, with an ordinary sieve. - Use those base primes to cross out composites inside a small buffer that covers only
[lo, hi].
This works because of the square root bound. Any composite m ≤ hi has a prime factor no larger than √m ≤ √hi. So the base primes are enough to cross out every composite in the range.
The Code
import math
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]
def segmented_sieve(lo, hi):
base = sieve(math.isqrt(hi))
mark = [True] * (hi - lo + 1)
for p in base:
start = max(p * p, ((lo + p - 1) // p) * p)
for m in range(start, hi + 1, p):
mark[m - lo] = False
return [lo + i for i, flag in enumerate(mark) if flag and lo + i >= 2]
print(segmented_sieve(100, 130)) # [101, 103, 107, 109, 113, 127]Finding the first multiple
The line that computes start is the core of the algorithm. (lo + p - 1) // p is the ceiling of lo / p. Multiplying it by p gives the smallest multiple of p that is at least lo.
Taking max with p * p does two things:
- It keeps
pitself from being crossed out whenplies inside the range, for example whenlois 2. - It skips multiples below p squared. Smaller primes already crossed those out, as in the plain sieve.
Index translation
The buffer index for number m is m - lo. Most bugs in segmented sieves are off-by-one errors here, or come from forgetting to filter out 0 and 1 when lo is small. The lo + i >= 2 check handles that case.
Cost
| Resource | Plain sieve up to hi | Segmented sieve on [lo, hi] |
|---|---|---|
| Memory | O(hi) | O(√hi + (hi − lo)) |
| Time | O(hi log log hi) | O(√hi log log hi + (hi − lo) log log hi) |
The time for the range part is roughly the range length times log log hi, plus one ceiling division per base prime.
Common Errors
- Sieving base primes only up to
√loinstead of√hi. Composites nearhithen survive. - Using float
math.sqrton huge values.math.isqrtis exact. - Starting at
lo // p * p, which can fall belowloand give a negative index.
Exercise
For lo = 100, hi = 130, and base prime p = 7, what value does start take, and which numbers in the range does p = 7 cross out?
Show answer
The ceiling of 100/7 is 15, and 15 * 7 = 105. max(49, 105) = 105, so start is 105. The pass crosses out 105, 112, 119, and 126.
Exercise
Why does segmented_sieve(1, 10) not report 2, 3, 5, or 7 as composite, even though each of them is a multiple of a base prime?
Show answer
The base primes are sieve(3) = [2, 3]. For p = 2, start = max(4, 2) = 4, and for p = 3, start = max(9, 3) = 9. Neither pass touches p itself. The number 5 is never a multiple of a base prime, and 7 is above both starts but is not a multiple of 2 or 3. The value 1 is removed by the lo + i >= 2 filter.