man number-theory/sieve

lesson 5 of 27 · Primes and factorization

The sieve of Eratosthenes

lib / Number theory for competitive programming 14 mindraft

checked against: proofs in the text, code tested with Python 3.15.2

code: toothywalrus/cp-math@lesson-05

Lesson 4 built the list of primes up to 10610^6 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 10610^6 in about a millisecond, and lists the 664,579 primes up to 10710^7 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 nn up to 400. Against lesson 4’s trial division, they compare sieve and sieve_flags with is_prime at 20 random n≤105n \le 10^5, and primes_up_to(10**6) with primes_by_trial(10**6). crossings is compared with a run that counts its writes, for every n<600n < 600. 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 2,3,…,n2, 3, \dots, n. 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 pp starts crossing at p2p^2, not 2p2p, and the whole thing stops once p2>np^2 > n:

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 n=60n = 60. Under each crossed-out number are the values of pp that crossed it:

The sieve on 1 to 60, one frame per value of pp. 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 n≥0n \ge 0 and 0≤m≤n0 \le m \le n, sieve(n)[m] is true exactly when mm is prime.

Proof. 0 and 1 start false and nothing sets an entry to true. For m≥2m \ge 2 there are two things to show.

A prime is never crossed out. Every number the loop crosses out is p⋅kp \cdot k with k≥p≥2k \ge p \ge 2, so it has the divisor pp with 1<p<pk1 < p < pk: it is composite.

A composite m≤nm \le n is crossed out. Let pp be its smallest prime factor. By lesson 4 (Lemmas 1 and 2), p≤m≤np \le \sqrt m \le \sqrt n, so the outer loop reaches pp. When it does, is_prime[p] is still true, since pp is prime and primes are never crossed out. And m=p⋅km = p \cdot k with k=m/p≥pk = m/p \ge p, so mm is one of p2,p2+p,…p^2, p^2 + p, \dots up to nn, which the inner loop crosses out. ■\blacksquare

The proof also says why the shortcuts lose nothing. A composite is crossed out by its smallest prime factor pp, at or after p2p^2, and with p≤np \le \sqrt n. So the multiples 2p,…,(p−1)p2p, \dots, (p-1)p that the inner loop skips are crossed out by a smaller prime, and no prime above n\sqrt n has work left to do. A composite value of pp, 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 pp writes once for each of p2,p2+p,…p^2, p^2 + p, \dots up to nn: that is ⌊(n−p2)/p⌋+1≤n/p\lfloor (n - p^2)/p \rfloor + 1 \le n/p writes, since p≥1p \ge 1. So the total number of writes is at most

W(n)≤∑p≤nnp=n∑p≤n1p,W(n) \le \sum_{p \le \sqrt n} \frac{n}{p} = n \sum_{p \le \sqrt n} \frac1p,

the sum over primes pp. How large that sum is was settled by Mertens in 1874.

Mertens’ second theorem. Summed over the primes p≤xp \le x,

∑p≤x1p=ln⁡ln⁡x+M+O ⁣(1ln⁡x),\sum_{p \le x} \frac1p = \ln \ln x + M + O\!\left(\frac{1}{\ln x}\right),

where M≈0.2615M \approx 0.2615 is the Meissel–Mertens constant.

This lesson does not prove it; the sources give the proof. Taken at x=nx = \sqrt n, where ln⁡ln⁡n=ln⁡ln⁡n−ln⁡2\ln \ln \sqrt n = \ln \ln n - \ln 2, it gives

W(n)≤nln⁡ln⁡n+(M−ln⁡2) n+O ⁣(nln⁡n)=nln⁡ln⁡n+O(n).W(n) \le n \ln \ln n + (M - \ln 2)\, n + O\!\left(\frac{n}{\ln n}\right) = n \ln \ln n + O(n).

Setting up the table costs nn more and the outer loop n\sqrt n steps, so the sieve runs in O(nlog⁡log⁡n)O(n \log \log n) 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, n−1−π(n)n - 1 - \pi(n) of them, are the least any sieve that crosses out each composite must write. The last column counts the writes when every prime p≤n/2p \le n/2 starts at 2p2p:

     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. ln⁡ln⁡n\ln \ln n grows so slowly (from 1.5 at 10210^2 to 2.9 at 10810^8) that the writes per number only went from 1.0 to 2.4 over this range. And about 61% of the writes at 10810^8 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 1/p1/p up to xx, minus ln⁡ln⁡x\ln \ln x:

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 n=107n = 10^7, 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 kk 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 10710^7, 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 10710^7 the bytearray sieve is cheap in both time and memory; at 10810^8 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 10810^8 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 nn and computes i * i for every prime ii:

// 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 463492=214822980146349^2 = 2148229801 does not fit in a 32-bit int. Signed overflow is undefined behaviour. Run with -fsanitize=undefined for every nn from 46340 to 46349, the sanitizer was silent up to 46348 and reported it at n=46349n = 46349, 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.

Try it yourself

  1. In sieve(100), which numbers are crossed out three times? Is any crossed out four times? How many times is 42 crossed out?
  2. Run the sieve up to 120. Which numbers does p=7p = 7 cross out that no smaller prime crossed out before it?
  3. For n=200n = 200, how many writes does sieve make? How many would it make if every prime p≤100p \le 100 started at 2p2p?
  4. Prove that after crossing out the even numbers above 2, it is enough to cross out p2,p2+2p,p2+4p,…p^2, p^2 + 2p, p^2 + 4p, \dots for each odd prime pp, which roughly halves the odd primes’ writes.
  5. Of the sieve’s 242,570,204 writes up to 10810^8, 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 n<2000n < 2000) by running the sieve’s loop and recording what it does, the 323 of 3 by adding up the ranges from 2p2p, and 5 with crossings.

Show the answers
  1. 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 {2,3,5,7}\{2, 3, 5, 7\} dividing it, so a multiple of 210. 42 is crossed out twice, by 2 and 3; 7 does not cross it out, because 42<72=4942 < 7^2 = 49.
  2. 49, 77, 91 and 119: 7⋅77 \cdot 7, 7⋅117 \cdot 11, 7⋅137 \cdot 13 and 7⋅177 \cdot 17, the multiples 7k≤1207k \le 120 with k≥7k \ge 7 whose kk has no prime factor below 7.
  3. 232 writes from p2p^2, against 323 from 2p2p.
  4. For odd pp, the multiples p2+p,p2+3p,…p^2 + p, p^2 + 3p, \dots are pp times an even number, so they are even and already crossed out. What is left is p⋅kp \cdot k for odd k≥pk \ge p: p2,p2+2p,…p^2, p^2 + 2p, \dots, half of the original list. The correctness proof goes through unchanged: the smallest prime factor of an odd composite mm is odd, and m/pm/p is odd.
  5. 148,331,660: the writes minus the 94,238,544 composites up to 10810^8, 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 O(nlog⁡log⁡n)O(n \log \log n) 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 O(1/log⁡n)O(1/\log n) error term, and F. Mertens, “Ein Beitrag zur analytischen Zahlentheorie”, J. reine angew. Math. 78 (1874), 46–62.
  • Wikipedia, Meissel–Mertens constant: M≈0.2614972128M \approx 0.2614972128.
  • cp-algorithms, Sieve of Eratosthenes: the (long long)i * i <= n check, the asymptotic analysis, and the vector<bool> against vector<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.