man number-theory/sieve
lesson 5 of 27 · Primes and factorization
The sieve of Eratosthenes
Lesson 4 built the list of primes up to by trial division, testing each number against the primes up to its square root: about 0.4 s in Python. The sieve of Eratosthenes turns the question around. Instead of asking, for each number, which primes divide it, it takes each prime and crosses out its multiples. What is never crossed out is prime. In Python it marks the primes up to in about a millisecond, and lists the 664,579 primes up to in about a tenth of a second. This lesson proves the sieve correct, counts its work, and shows the version that is fast in Python and the table types that matter in C++.
The code is in cp-math at tag lesson-05,
in cpmath/sieve.py. Its tests compare sieve, sieve_flags,
primes_up_to and count_primes with brute force for every up to
400. Against lesson 4’s trial division, they compare sieve and
sieve_flags with is_prime at 20 random , and
primes_up_to(10**6) with primes_by_trial(10**6). crossings is
compared with a run that counts its writes, for every . python3 -m cpmath.lesson05 prints
every Python output on this page (--time adds the timings). The C++
output comes from demos/sieve.cpp in the same repo.
Crossing out multiples
Write down . The smallest number, 2, is prime: cross out its multiples. The smallest number left after 2, which is 3, is prime: cross out its multiples. Go on like that. Two shortcuts make it cheaper. Each prime starts crossing at , not , and the whole thing stops once :
def sieve(n):
"""is_prime[0..n] as a list of bools (n >= 0): the sieve of
Eratosthenes, crossing out the multiples of each prime p from p*p."""
is_prime = [i >= 2 for i in range(n + 1)]
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 is_prime
The figure runs it for . Under each crossed-out number are the values of that crossed it:
The sieve of Eratosthenes on 1 to 60. p = 2 crosses out 4, 6, ..., 60; p = 3 crosses out 9, 12, ..., 60, half of which were already crossed; p = 4 is skipped; p = 5 crosses out 25, 30, ..., 60; p = 6 is skipped; p = 7 crosses out 49 and 56. At p = 8, 64 > 60 and the loop stops: the 17 numbers left, 2 to 59, are the primes. (This figure steps through a recorded run; it needs JavaScript.)
The sieve on 1 to 60, one frame per value of . The labels under a
number are the primes that crossed it out. Trace from
python3 -m cpmath.sieve_trace 60 in cp-math.
Why it is correct
Theorem. For and , sieve(n)[m] is true
exactly when is prime.
Proof. 0 and 1 start false and nothing sets an entry to true. For there are two things to show.
A prime is never crossed out. Every number the loop crosses out is with , so it has the divisor with : it is composite.
A composite is crossed out. Let be its smallest prime
factor. By lesson 4 (Lemmas 1 and 2), , so the
outer loop reaches . When it does, is_prime[p] is still true, since
is prime and primes are never crossed out. And with
, so is one of up to ,
which the inner loop crosses out.
The proof also says why the shortcuts lose nothing. A composite is crossed
out by its smallest prime factor , at or after , and with
. So the multiples that the inner
loop skips are crossed out by a smaller prime, and no prime above
has work left to do. A composite value of , like 4 or 6 in
the figure, finds is_prime[p] already false and is skipped. That is only
a saving: crossing out its multiples would cross out composites again.
What it costs
Prime writes once for each of up to : that is writes, since . So the total number of writes is at most
the sum over primes . How large that sum is was settled by Mertens in 1874.
Mertens’ second theorem. Summed over the primes ,
where is the Meissel–Mertens constant.
This lesson does not prove it; the sources give the proof. Taken at , where , it gives
Setting up the table costs more and the outer loop steps, so
the sieve runs in time. That is an upper bound on the
writes, not their exact number. The exact number comes from crossings,
which adds up the length of each prime’s range (the tests check it against
a run that counts its writes); here it is next to the bound and to two
other numbers. The composites, of them, are the
least any sieve that crosses out each composite must write. The last
column counts the writes when every prime starts at :
n writes n*sum 1/p, p<=sqrt n n ln ln n composites from 2p
10^2 104 118 153 74 146
10^3 1411 1566 1933 831 1958
10^4 16981 18028 22203 8770 23071
10^5 193078 202252 244347 90407 256808
10^6 2122048 2198080 2625792 921501 2775210
10^7 22850051 23492699 27799426 9335420 29465738
10^8 242570204 248305995 291347399 94238544 309275826
Three things to read off it. The writes stay under the bound in every row, as they must. grows so slowly (from 1.5 at to 2.9 at ) that the writes per number only went from 1.0 to 2.4 over this range. And about 61% of the writes at hit an entry that was already crossed out: 242,570,204 writes for 94,238,544 composites. The next lesson’s linear sieve writes each composite exactly once.
The constant itself shows up in a run too. The sum of up to , minus :
x = 10^1: sum of 1/p = 1.1762, minus ln ln x = 0.3422
x = 10^2: sum of 1/p = 1.8028, minus ln ln x = 0.2756
x = 10^3: sum of 1/p = 2.1981, minus ln ln x = 0.2654
x = 10^4: sum of 1/p = 2.4831, minus ln ln x = 0.2627
x = 10^5: sum of 1/p = 2.7053, minus ln ln x = 0.2618
x = 10^6: sum of 1/p = 2.8873, minus ln ln x = 0.2615
x = 10^7: sum of 1/p = 3.0414, minus ln ln x = 0.2615
x = 10^8: sum of 1/p = 3.1750, minus ln ln x = 0.2615
M = 0.2615; M - ln 2 = -0.4316
These values agree with the theorem; they do not prove it.
A fast version in Python
sieve does every write in Python’s own loop: 22,850,051 of them for
, each a trip round the interpreter. A bytearray can take all of
one prime’s writes at once, as a slice assignment that runs in C:
def sieve_flags(n):
"""The same table as a bytearray of 0s and 1s (n >= 0). Each prime's
multiples are cleared by one slice assignment, which runs in C."""
flags = bytearray([1]) * (n + 1)
flags[:2] = bytes(min(2, n + 1))
for p in range(2, isqrt(n) + 1):
if flags[p]:
flags[p * p::p] = bytes(len(range(p * p, n + 1, p)))
return flags
def primes_up_to(n):
"""All primes p <= n, increasing."""
return list(compress(range(n + 1), sieve_flags(n)))
def count_primes(n):
"""pi(n), the number of primes p <= n."""
return sieve_flags(n).count(1)
bytes(k) is zero bytes, and len(range(p * p, n + 1, p)) is exactly
the length of the slice flags[p * p::p]. It has to be: assigning to a
slice with a step needs a right-hand side of the same length, or Python
raises ValueError. itertools.compress keeps the numbers whose flag is 1.
One recorded run on an Apple M2 Pro, Python 3.15.2:
primes_by_trial(10**6): 0.389 s
sieve(10**6): 0.041 s
sieve_flags(10**6): 0.001 s
sieve(10**7): 0.779 s
sieve_flags(10**7): 0.013 s
primes_up_to(10**7): 0.106 s
count_primes(10**8): 0.343 s
primes_up_to(10**8): 1.218 s
These are single runs on a machine doing other work, so read them to one
significant figure. The slices made the sieve roughly 60 times faster at
, and building the list of primes then costs more than the sieve.
Memory matters as much. A list holds an 8-byte pointer per entry; a
bytearray holds one byte:
sys.getsizeof(sieve(10**7)) = 89095160
sys.getsizeof(sieve_flags(10**7)) = 10000098
sys.getsizeof([True] * (10**7 + 1)) = 80000064
(The comprehension’s list came out 9 MB larger than [True] * (n + 1),
probably room left over from growing the list as the comprehension
appended to it.) So up to about the
bytearray sieve is cheap in both time and memory; at it still
counts the primes in under half a second, but the list of 5,761,455 primes
costs over a second to build.
In C++: the table and an overflow
C++ offers three tables of flags, and the choice decides the memory. The demo measures each with an allocator that adds up what it is asked for:
vector<bool>(10^8 + 1) allocates 12500008 bytes
vector<char>(10^8 + 1) allocates 100000001 bytes
sizeof(bitset<10^8 + 1>) = 12500008 bytes
vector<bool> pi(10^8) = 5761455 0.59 s
vector<char> pi(10^8) = 5761455 0.31 s
bitset pi(10^8) = 5761455 0.59 s
That is Apple clang 21 with -O2 and its libc++. The standard allows
vector<bool> to store one bit per element but does not require it (whether
it is packed at all is up to the implementation); libc++ packs it, so it
takes an eighth of vector<char>’s memory. bitset also packs bits, but
its size is fixed when compiling. In this run, and in reruns that varied by
up to 0.05 s, the vector<char> version took about half the time of the
packed ones. That time covers allocating the vectors, filling the table
element by element, sieving and
counting, and for the packed tables the filling and counting go bit by
bit; the demo does not time the parts separately, so it does not show
which table sieves faster. cp-algorithms, on its machine, reports
vector<bool> 1.4 to 1.7 times faster than vector<char> for this sieve.
The memory does not depend on any of that: 100 MB against 12.5 MB at
can decide whether the sieve fits a 64 MB limit at all, and how
much of a 256 MB one is left for the rest of the solution.
A bitset that large belongs in static storage, as in the demo. Declared
as a local variable it lives on the stack: --local-bitset puts it there
and the program was killed by a segmentation fault (exit status 139). The
stack limit here (ulimit -s) is 8176 KB, and the bitset is 12.5 MB.
The overflow in i * i
The demo’s sieve stops the outer loop with i <= n / i, which cannot
overflow. A common version lets the outer loop run to and computes
i * i for every prime :
// The common bug: the outer loop runs to n, and i * i overflows once a
// prime i above 46340 is reached (46341 * 46341 > 2^31 - 1).
int count_primes_overflowing(int n) {
std::vector<char> is_prime(n + 1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i <= n; i++)
if (is_prime[i])
for (int j = i * i; j <= n; j += i) is_prime[j] = false;
int count = 0;
for (int i = 0; i <= n; i++) count += is_prime[i];
return count;
}
The first prime above 46340 is 46349, and does not
fit in a 32-bit int. Signed overflow is undefined behaviour. Run with
-fsanitize=undefined for every from 46340 to 46349, the sanitizer
was silent up to 46348 and reported it at , a limit far below
any real sieve size:
demos/sieve.cpp:48:28: runtime error: signed integer overflow: 46349 * 46349 cannot be represented in type 'int'
That build then reported an overflowing pointer offset inside libc++’s
vector and died of a bus error in count_primes_overflowing; the -O2
build died with a bus error too (exit status 138), without printing
anything. Neither outcome is guaranteed. The fix is to
loop only while i <= n / i, as the demo’s sieve does, or to test
(long long)i * i <= n as cp-algorithms does.
Practice problems
Each needs an idea from this lesson. Links go to the problem pages; the one line is what to use, not the statement.
- LeetCode 204. Count Primes: the primes strictly below , so
count_primes(n - 1), and 0 when ( can be 0). - LeetCode 1175. Prime Arrangements: with , the answer is mod .
- LeetCode 2523. Closest Prime Numbers in Range: sieve up to
right, scan neighbouring primes in the range for the smallest gap (the first pair on a tie), and return when the range holds fewer than two primes. - LeetCode 2761. Prime Pairs With Target Sum: one sieve up to , then test and for each .
- LeetCode 2601. Prime Subtraction Operation: primes below 1000 from a sieve; left to right, subtract the largest prime below
nums[i] - previf there is one, and fail when the value is not above the previous one. - LeetCode 3233. Find the Count of Numbers Which Are Not Special: the special numbers are the squares of primes, so sieve only up to and subtract the primes with from the range’s length.
- Codeforces 17A. Noldbach problem: sieve up to , walk the consecutive pairs of primes, test whether their sum plus one is a prime up to , and compare the count with .
- Codeforces 776B. Sherlock and his girlfriend: primes get one colour and composites the other, so a sieve up to colours everything; for one colour is enough.
Try it yourself
- In
sieve(100), which numbers are crossed out three times? Is any crossed out four times? How many times is 42 crossed out? - Run the sieve up to 120. Which numbers does cross out that no smaller prime crossed out before it?
- For , how many writes does
sievemake? How many would it make if every prime started at ? - Prove that after crossing out the even numbers above 2, it is enough to cross out for each odd prime , which roughly halves the odd primes’ writes.
- Of the sieve’s 242,570,204 writes up to , how many hit an entry that was already crossed out?
Answers
Each one is asserted in tests/test_lesson05.py: 1, 2, the 232 of 3 and
the claim of 4 (for every ) by running the sieve’s loop and
recording what it does, the 323 of 3 by adding up the ranges from ,
and 5 with crossings.
Show the answers
- 30, 60, 70, 84 and 90, each by three of 2, 3, 5 and 7. None is crossed out four times: that needs four primes from dividing it, so a multiple of 210. 42 is crossed out twice, by 2 and 3; 7 does not cross it out, because .
- 49, 77, 91 and 119: , , and , the multiples with whose has no prime factor below 7.
- 232 writes from , against 323 from .
- For odd , the multiples are times an even number, so they are even and already crossed out. What is left is for odd : , half of the original list. The correctness proof goes through unchanged: the smallest prime factor of an odd composite is odd, and is odd.
- 148,331,660: the writes minus the 94,238,544 composites up to , each of which is crossed out for the first time exactly once.
Sources
- Wikipedia, Sieve of Eratosthenes: the algorithm, starting each prime at its square, the operation count from the sum of prime reciprocals, and the earliest known reference, in Nicomachus’s Introduction to Arithmetic.
- Wikipedia, Mertens’ theorems: the second theorem as stated above, with the error term, and F. Mertens, “Ein Beitrag zur analytischen Zahlentheorie”, J. reine angew. Math. 78 (1874), 46–62.
- Wikipedia, Meissel–Mertens constant: .
- cp-algorithms, Sieve of Eratosthenes: the
(long long)i * i <= ncheck, the asymptotic analysis, and thevector<bool>againstvector<char>measurements quoted above. - cppreference, std::vector<bool> (a possibly space-efficient specialization) and std::bitset.
ls number-theory/
Divisibility and the Euclidean algorithm
- 01 GCD, Euclid, and Bézout draftWhy gcd(a, b) = gcd(b, a mod b), why it takes so few steps, extended Euclid and ax + by = c. Unlocks gcd-of-array, water jug and lcm problems.
- 02 Integer division, floors and ceilings draft// and % on negative numbers in Python and C++, ceiling division without floats, math.isqrt. Unlocks problems whose answer is a count of multiples in a range.
- 03 GCD over arrays and subarrays draftPrefix and suffix gcds, the gcd of differences, why a subarray's gcd changes only a logarithmic number of times. Unlocks subarray-gcd counting and remove-one-element problems.
Primes and factorization
- 04 Primality and factoring by trial division draftWhy checking up to the square root suffices, and how far that goes in a time limit. Unlocks single-number primality and factorization queries.
- 05 The sieve of Eratosthenes draftCrossing out multiples from p squared, its n log log n cost, and a fast bytearray version in Python. Unlocks prime counting and prime listing up to about ten million.
- 06 The linear sieve draftEach composite crossed out exactly once, by its smallest prime factor, with multiplicative functions computed in the same pass.
- 07 Smallest-prime-factor sieve draftStore each number's smallest prime factor and factor any number below the limit in logarithmic time. Unlocks problems that factor many numbers.
- 08 The segmented sieve plannedPrimes in a window [L, R] with R far beyond what fits in memory, using only the primes up to the square root of R.
- 09 Number and sum of divisors plannedBoth from the prime factorization, listing all divisors, and the harmonic-series sieve that does it for every n at once. Unlocks divisor-counting and perfect-number problems.
- 10 Prime powers in factorials plannedLegendre's formula for the exponent of p in n!. Unlocks trailing-zero and divisibility-of-factorial problems.
Modular arithmetic
- 11 Arithmetic mod m plannedCongruences, the remainder of a negative number, which operations survive reduction, and why so many problems use 10^9 + 7.
- 12 Fast exponentiation plannedSquare-and-multiply, Python's three-argument pow, and matrix powers for linear recurrences. Unlocks huge-exponent and n-th Fibonacci problems.
- 13 Modular inverses plannedDivision mod m by Fermat's little theorem and by extended Euclid, when an inverse exists, and all inverses of 1..n in linear time.
- 14 Euler's totient and Euler's theorem plannedCounting the numbers coprime to n, by formula and by sieve, and reducing exponents mod phi(m). Unlocks power towers mod m.
- 15 Linear congruences plannedSolving a x ≡ b (mod m), how many solutions there are, and when there are none.
- 16 The Chinese remainder theorem plannedCombining congruences into one, for coprime and non-coprime moduli. Unlocks problems with several periodic conditions.
- 17 Orders, primitive roots and discrete logarithms plannedThe order of an element, finding a generator, and baby-step giant-step for a^x ≡ b (mod m).
Counting mod p
- 18 Factorials, inverse factorials and nCr plannedPrecompute factorials and their inverses once, then answer each binomial coefficient in constant time. Unlocks most counting problems with a prime modulus.
- 19 Binomial identities and Pascal's triangle plannedPascal's rule for composite moduli, stars and bars, and Catalan numbers.
- 20 Lucas's theorem plannednCr mod a small prime p when n is far larger than p, digit by digit in base p.
- 21 Inclusion–exclusion plannedCounting by alternating sums over subsets: numbers coprime to n in a range, derangements, surjections.
- 22 The Möbius function and Möbius inversion plannedInclusion–exclusion over divisors. Unlocks counting coprime pairs and sums of gcds.
- 23 Divisor blocks: iterating over n // i plannedn // i takes only about 2 sqrt(n) distinct values; summing over blocks of equal value turns many O(n) sums into O(sqrt n).
- 24 Sums over gcds plannedSums of gcd(i, n) and of gcd(i, j) over a grid, by grouping on the gcd and using the totient and Möbius function.
Large numbers
- 25 The Miller–Rabin primality test plannedA probabilistic test, and a fixed set of bases that makes it exact for every 64-bit number. Unlocks primality checks up to 10^18.
- 26 Pollard's rho factorization plannedFactoring 64-bit numbers by finding a cycle in a pseudo-random sequence, with Brent's improvement.
- 27 Floor sums by a Euclid-like recursion plannedThe sum of floor((a i + b) / m) over a range in logarithmic time, by the same reduction Euclid's algorithm uses. Unlocks lattice-point counting under a line.