Sub topic 10
Why the Sieve Runs in O(n log log n) Time
This chapter assumes you can read the sieve(n) function from earlier chapters and know why each pass starts at p². It also assumes you know introductory Big-O notation and the prime number theorem's statement that primes near t have density about 1/ln t. The goal is to count the sieve's work exactly enough to see where the unusual log log n factor comes from, and to see what that bound does and does not tell you about real running time.
Where the Work Happens
The sieve has three parts, and each one costs a different amount.
- Allocation.
[True] * (n + 1)touches every slot once: O(n). - The outer loop.
pruns from 2 whilep * p <= n, so it makes about √n iterations, and each one does a constant-timeis_prime[p]check: O(√n). - The inner loop. For each prime p ≤ √n, it crosses out p², p² + p, … up to n.
- Collecting the result. The final list comprehension scans all n + 1 flags: O(n).
Parts 1, 2, and 4 add up to O(n). The inner loop is the only part that can cost more than linear time, so the analysis is about counting crossings.
Counting Crossings for One Prime
For a single prime p, the inner loop visits p², p² + p, p² + 2p, … while the value is at most n. The number of visits is
floor((n − p²) / p) + 1, which is roughly n/p − p.
For n = 100 the four passes look like this:
| Prime p | First value | Last value | Crossings | n/p for comparison |
|---|---|---|---|---|
| 2 | 4 | 100 | 49 | 50 |
| 3 | 9 | 99 | 31 | 33.3 |
| 5 | 25 | 100 | 16 | 20 |
| 7 | 49 | 98 | 8 | 14.3 |
| Total | 104 | 117.6 |
Starting at p² subtracts about p crossings from each pass. That is a real saving for small n, but it does not change the asymptotic bound, as the next section shows.
Summing Over All Primes
Add up the passes and the total crossing count is approximately
n · (1/2 + 1/3 + 1/5 + 1/7 + … ) taken over primes p ≤ √n, minus the sum of those primes.
The subtracted term is Σ p for p ≤ √n. There are about √n / ln √n such primes, each at most √n, so this sum is O(n / log n). That is smaller than n, so you can drop it. What remains is n times the sum of prime reciprocals up to √n.
The Sum of Prime Reciprocals Grows Like ln ln x
Mertens' second theorem states that
Σ (1/p) for p ≤ x = ln ln x + M + o(1), where M ≈ 0.2615.
The prime number theorem gives a quick way to see why. Primes near t occur with density about 1/ln t, so the sum behaves like an integral that weights each 1/t by that density:
∫ from 2 to x of 1 / (t ln t) dt = ln ln x − ln ln 2.
Substituting u = ln t turns the integrand into 1/u, and integrating 1/u gives ln u = ln ln t.
Now plug in x = √n:
ln ln √n = ln(½ ln n) = ln ln n − ln 2.
The subtracted ln 2 is a constant, so the sum up to √n is still ln ln n + O(1). Multiply by n and you have the bound:
total crossings = n ln ln n + O(n), which is O(n log log n).
The base of the logarithm only changes constants, so writing log log n in Big-O is standard.
Why Skipping Composites Matters
Suppose the outer loop forgot the if is_prime[p] test and crossed out multiples of every d from 2 to √n. The total would become n times the harmonic sum Σ 1/d for d ≤ √n, which grows like ln √n = ½ ln n. That version is O(n log n).
The is_prime[p] check is what turns ln n into ln ln n. Composites appear much more often than primes, so the reciprocal sum over primes is far smaller than the full harmonic sum.
At n = 10^12, ln ln n is about 3.3. For any n you can store in memory, the sieve behaves like a linear algorithm with a constant factor of roughly 2 to 3.
Measuring It
The script below counts crossings and compares them with ln ln n. It can also run the "every d" variant so you can watch the harmonic sum take over.
import math
def count_crossings(n, only_primes=True):
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
crossings = 0
p = 2
while p * p <= n:
if is_prime[p] or not only_primes:
for m in range(p * p, n + 1, p):
is_prime[m] = False
crossings += 1
p += 1
return crossings
print(f"{'n':>9} {'primes/n':>9} {'all d/n':>9} {'lnln n':>7} {'ln n':>6}")
for n in [10**3, 10**4, 10**5, 10**6]:
c_primes = count_crossings(n, only_primes=True)
c_all = count_crossings(n, only_primes=False)
print(f"{n:>9} {c_primes / n:9.3f} {c_all / n:9.3f} "
f"{math.log(math.log(n)):7.3f} {math.log(n):6.3f}")When you run it, the primes/n column grows very slowly. It sits a little below ln ln n because of the constant M − ln 2 ≈ −0.43 and the p² savings. The all d/n column grows noticeably faster, roughly in step with ½ ln n. The gap between the two columns is the gap between O(n log log n) and O(n log n).
A Second View: Redundant Crossings
There is another way to read the bound. A composite m ≤ n gets crossed out once for each distinct prime factor p with p² ≤ m. For example, 30 is crossed out by 2, 3, and 5. The Hardy–Ramanujan theorem says a typical integer near n has about ln ln n distinct prime factors. So the sieve performs about ln ln n crossings per number on average, and n ln ln n in total.
From this view the extra factor is wasted work. Each composite only needs to be marked once, and each repeated mark is redundant. The linear sieve (also called the Euler sieve) marks every composite exactly once, through its smallest prime factor, and runs in O(n). It does this by keeping a list of primes found so far and doing more bookkeeping on each step.
| Sieve | Time | Extra memory | Practical notes |
|---|---|---|---|
| Eratosthenes, all d | O(n log n) | O(n) flags | Only a teaching example |
| Eratosthenes, primes only | O(n log log n) | O(n) flags | Simple inner loop with sequential access; easy to segment |
| Linear (Euler) sieve | O(n) | O(n) flags + prime list | More branches and scattered writes; often no faster in practice |
Memory: O(n), but Watch the Constant
The sieve keeps one flag per integer up to n, so memory is Θ(n). The constant depends on the data structure:
| Representation | Bytes per number | Memory for n = 10^9 |
|---|---|---|
| Python `list` of `bool` | 8 (one pointer per slot in CPython) | about 8 GB |
| `bytearray` | 1 | about 1 GB |
| Odd-only `bytearray` | 0.5 | about 500 MB |
| Odd-only bit array | 1/16 | about 62.5 MB |
Odd-only and bit-packed layouts are the topic of the next chapter. They cut memory by a constant factor, so the bound stays Θ(n).
Gotchas in Reading the Bound
"Linear-ish" Is Measured in n, Not in Input Size
The input to the sieve is a single number n, which takes about log₂ n bits to write down. Relative to that input size, O(n log log n) is exponential. This is why sieving is fine for listing all primes up to 10^9 but useless for checking whether one 300-digit number is prime. That job calls for a probabilistic test, not a table.
The Operation Count Ignores the Memory Hierarchy
The analysis treats every crossing as constant time. That holds while the flag array fits in CPU cache. Once n reaches tens of millions, the array no longer fits, and passes for small p sweep the whole array from main memory again and again. Real running time then grows faster than the crossing count predicts. The segmented sieve, covered in a later chapter, fixes this by sieving one cache-sized block at a time, with the same O(n log log n) crossings.
Stopping the Outer Loop Early Is Required for the Bound
If the outer loop ran p all the way to n, the extra iterations would cost O(n) checks, which does not hurt the Big-O. But a version that started each pass at 2p instead of p² and also looped p up to n would add Σ n/p over primes up to n, that is n ln ln n, roughly doubling the work. Keep both the p² start and the √n stop.
Exercises
Exercise
Count the exact number of crossings the sieve performs for n = 50, pass by pass.
Show answer
p = 2 crosses 4, 6, ..., 50: 24 crossings. p = 3 crosses 9, 12, ..., 48: 14 crossings. p = 5 crosses 25, 30, ..., 50: 6 crossings. p = 7 crosses only 49: 1 crossing. The loop stops at p = 8 because 64 > 50. Total: 45 crossings.
Exercise
Removing the if is_prime[p] check still gives correct output. Why does it change the running time from O(n log log n) to O(n log n)?
Show answer
Without the check, the inner loop runs for every d up to √n, so total work is about n times the sum of 1/d over all d ≤ √n. That harmonic sum grows like ½ ln n. With the check, the sum covers only primes, and by Mertens' theorem the sum of 1/p up to √n grows like ln ln n.
Exercise
The sum of 1/p is taken only up to √n, yet the result is still ln ln n + O(1). Show why the square root changes only the constant.
Show answer
ln ln √n = ln(½ ln n) = ln ln n − ln 2. The ln 2 is a constant, so multiplying by n contributes only O(n), which the n ln ln n term absorbs.
Exercise
You need all primes below 2 × 10^9 on a machine with 4 GB of free RAM. Which representations from the memory table work for a plain (non-segmented) sieve, and what does the crossing count tell you about running time?
Show answer
A Python list needs about 16 GB and a bytearray about 2 GB, so the bytearray just fits and the odd-only variants fit easily. The crossing count is about n(ln ln n − 0.43), roughly 2.6 × 2 × 10^9 ≈ 5 × 10^9 operations. That is feasible in a compiled language. At this size the array does not fit in cache, so expect real time to be worse than the count suggests. A segmented sieve would help.