Sub topic 12
Sieving Large Ranges with a Segmented Sieve
This chapter assumes you already know the plain sieve of Eratosthenes, why each crossing-out pass starts at p squared, and why the sieve costs O(n log log n) time and O(n) memory. It also assumes you can read Python with loops, lists, and slices.
The plain sieve has one practical limit: it allocates one flag for every number from 0 to n. That is fine for n = 10^7. For n = 10^12 it is not. You may also need primes in only a narrow window, such as between 10^12 and 10^12 + 10^6, and allocating a trillion flags to read a million of them wastes almost all of the memory. A segmented sieve solves both problems. It uses the same crossing-out idea, but it works on one window of numbers at a time.
The Key Observation
Recall the square root bound. Every composite number m has a prime factor no larger than √m. So if you want to know which numbers in a range [lo, hi] are composite, you only need the primes up to √hi. Those are the base primes.
This splits the work into two parts:
- Run an ordinary sieve up to √hi to get the base primes. This part is small. For hi = 10^12, √hi = 10^6, and there are only 78,498 primes below a million.
- Allocate a buffer with one flag per number in [lo, hi]. For each base prime p, cross out the multiples of p that fall inside the buffer. Whatever stays unmarked is prime.
The buffer is indexed by offset. Position i in the buffer stands for the number lo + i.
The Basic Implementation
Here is a complete, runnable version. It includes the plain sieve from earlier in the tutorial, because the segmented sieve calls it to build its base primes.
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 in Range
The only new arithmetic is the line that computes start. It combines two candidates.
The expression ((lo + p - 1) // p) * p gives the smallest multiple of p that is at least lo. Adding p - 1 before the floor division rounds up instead of down, so it computes ⌈lo / p⌉ · p using integers only. For lo = 100 and p = 7, that is (106 // 7) · 7 = 15 · 7 = 105.
The p * p candidate is the same rule as in the plain sieve. Any multiple of p smaller than p² has a smaller prime factor, so a smaller base prime already crosses it out. Taking the maximum skips that redundant work. It also does a more important job, which the next section explains.
Why the `max` with p² Is Required, Not Optional
Suppose lo = 2 and you drop the max and write start = ((lo + p - 1) // p) * p. For p = 2 that gives start = 2, so the loop marks 2 itself as composite. The same happens to 3, 5, and every other base prime inside the range. When the range overlaps the base primes, the p² lower bound keeps you from crossing out p itself.
When lo is far above √hi, p² is always less than lo, so the max picks the rounded-up multiple and does nothing visible. That is why this bug often goes unnoticed. Tests on high windows pass, and the code only fails when someone calls it with a small lo.
Processing a Huge Range in Fixed Blocks
The function above still allocates hi - lo + 1 flags. That is fine for a window of a million numbers. To enumerate or count all primes up to 10^10, though, the buffer would again be enormous. The fix is to cut [lo, hi] into blocks of fixed size and sieve each block in turn, reusing the same base primes.
Block size matters for speed. A block that fits in the CPU's L1 or L2 cache (tens to hundreds of kilobytes) keeps every crossing-out write in fast memory. A plain sieve over 10^9 flags jumps across a gigabyte of RAM for each prime, and that is cache-hostile.
This version yields primes one at a time and uses a bytearray with slice assignment. The slice assignment does the crossing out in C instead of a Python loop.
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 primes_in_blocks(lo, hi, block_size=32768):
base = sieve(math.isqrt(hi))
for seg_lo in range(lo, hi + 1, block_size):
seg_hi = min(seg_lo + block_size - 1, hi)
mark = bytearray(b"\x01") * (seg_hi - seg_lo + 1)
for p in base:
if p * p > seg_hi:
break
start = max(p * p, ((seg_lo + p - 1) // p) * p)
first = start - seg_lo
mark[first::p] = bytes(len(range(first, len(mark), p)))
for i, flag in enumerate(mark):
n = seg_lo + i
if flag and n >= 2:
yield n
print(list(primes_in_blocks(100, 130, block_size=7)))
# [101, 103, 107, 109, 113, 127]
print(sum(1 for _ in primes_in_blocks(1, 10**6)))
# 78498
print(next(primes_in_blocks(10**12, 10**12 + 100)))
# 1000000000039The last call finds the first prime above one trillion. It builds base primes up to 10^6 and a single 101-byte block. A plain sieve would need about a terabyte for the same answer.
Two details in this version are worth noticing:
- The
breakwhenp * p > seg_histops early in the low blocks. Larger base primes have no multiples of p² or above in this block, so they have nothing to cross out. - If
firstis past the end of the block, the slicemark[first::p]is empty andlen(range(...))is 0, so the assignment does nothing. No special case is needed.
Cost Analysis
Let R = hi − lo + 1 be the range length and r = √hi.
| Quantity | Plain sieve up to hi | Segmented sieve, one buffer | Segmented sieve, blocks of size B |
|---|---|---|---|
| Memory for flags | O(hi) | O(R) | O(B) |
| Memory for base primes | none | O(r / log r) | O(r / log r) |
| Time | O(hi log log hi) | O(r log log r + R log log hi + π(r)) | same as one buffer, plus O(π(r)) per block |
| Flags for hi = 10^12, R = 10^6 | 10^12 | 10^6 + 78,498 base primes | B + 78,498 base primes |
Here π(r) is the number of primes up to r. The crossing-out work in a window of length R is about the sum of R/p over the base primes, which grows like R log log hi. The per-block overhead comes from computing start once for every base prime in every block. If B is much smaller than π(r), that overhead dominates. So pick B to be at least about √hi when you can, and still small enough to fit in cache.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Base primes up to √(hi − lo) instead of √hi | Composites with a large smallest factor survive | Sieve base primes up to `math.isqrt(hi)` |
| `int(math.sqrt(hi))` for very large hi | Off by one when float rounding drops the true root | Use `math.isqrt`, which is exact |
| Missing `max(p * p, ...)` | Base primes inside the range are reported as composite | Keep the p² lower bound |
| No filter for 0 and 1 | 0 and 1 appear in the output when lo < 2 | Filter `lo + i >= 2` |
| Treating hi as exclusive | Misses hi when hi is prime | Size the buffer `hi - lo + 1` and loop to `hi + 1` |
| Rebuilding base primes per block | Slow, with time growing with the number of blocks | Compute `base` once, outside the block loop |
When to Use It
Use a segmented sieve when you need all primes in a window whose upper end is too large for an O(hi) array, or when you need every prime up to N and memory or cache behavior matters. Use trial division or a probabilistic test when you need to check only a handful of isolated large numbers. Sieving a window makes sense only once the window holds enough candidates to pay for the base-prime setup.
Exercise
You call segmented_sieve(1, 50) but you wrote start = ((lo + p - 1) // p) * p without the max. Which numbers are wrongly missing from the output, and why?
Show answer
The base primes are the primes up to isqrt(50) = 7: 2, 3, 5, and 7. For each one, the first multiple at or above lo = 1 is p itself, so p gets crossed out. The output therefore leaves out 2, 3, 5, and 7. Adding max(p * p, ...) makes each pass start at 4, 9, 25, and 49, so the base primes survive.
Exercise
For lo = 1012 and hi = 1012 + 10**6, how many flags does segmented_sieve allocate, how many base primes does it use, and roughly how much memory would a plain sieve up to hi need with one byte per flag?
Show answer
The buffer has hi - lo + 1 = 1,000,001 flags. The base primes are the primes up to isqrt(hi) = 1,000,000, and there are 78,498 of them. A plain sieve would need about 10^12 bytes, roughly one terabyte.
Exercise
In primesinblocks, why is it safe to break out of the base-prime loop as soon as p * p > seg_hi, instead of using continue?
Show answer
The base primes are in increasing order. Once p p > seg_hi, every later base prime q > p also has q q > seg_hi. Each pass starts at max(q q, ...), which is at least q q, so none of those primes has a starting point inside the block. None of them would cross anything out, so stopping the loop gives the same result as continuing it.