man number-theory/linear-sieve
lesson 6 of 27 · Primes and factorization
The linear sieve
Up to , lesson 5’s sieve made 2,122,048 writes to cross out 921,501 composites: 1,200,547 of the writes hit a number already crossed out, the way 30 is crossed out by 2, 3 and 5. The linear sieve writes each composite exactly once, as where is its smallest prime factor. It does work instead of , and it leaves behind a table of every number’s smallest prime factor. From that table the same pass can compute the number of divisors, Euler’s or the Möbius function of every number up to . Linear does not mean faster, though, and this lesson measures that too.
The code is in cp-math at tag lesson-06,
in cpmath/linear_sieve.py. Its tests check linear_sieve against brute
force for every up to 300; its list of primes up to against
lesson 4’s primes_by_trial and lesson 5’s primes_up_to; its table at
3,000 random against lesson 4’s smallest_prime_factor; and
they count the writes to every entry up to 5000. Each
function of the second half is checked for every up to 2000, against
a brute-force count (, , ) or lesson 4’s factorize
(, ), and against the factorization at 2000 random
( at 100 other random , by counting gcds).
python3 -m cpmath.lesson06 prints every Python output on this page
(--time adds the timings). The C++ output comes from
demos/linear_sieve.cpp.
One write per composite
Write for the smallest prime factor of . Every composite splits as with and , and no prime factor of is smaller than , so . The linear sieve runs that split backwards: for each , it multiplies by every prime and records as the smallest prime factor of .
def linear_sieve(n):
"""(lp, primes) for n >= 0: lp[m] is the smallest prime factor of m
for 2 <= m <= n (lp[0] = lp[1] = 0), primes the primes up to n.
Invariant: when the outer loop is at i, every lp[m] with m <= i is
final. The inner loop writes lp[i * p] = p for the primes p up to
lp[i], so each composite is written once, by i = m // lp[m]."""
lp = [0] * (n + 1)
primes = []
for i in range(2, n + 1):
if lp[i] == 0:
lp[i] = i
primes.append(i)
for p in primes:
if p > lp[i] or i * p > n:
break
lp[i * p] = p
return lp, primes
An lp[i] still 0 when the loop reaches means nothing wrote it, so
is prime, and its smallest prime factor is itself. The figure runs it
for . Each composite is labelled with the that wrote it:
The linear sieve on 1 to 50. i = 2 writes 4; i = 3 writes 6 and 9; i = 4 writes 8 and stops, since 3 is more than lp(4) = 2; i = 5 writes 10, 15 and 25; and so on up to i = 25, which writes 50. Each of the 34 composites is written once, labelled with the i and p that wrote it. (This figure steps through a recorded run; it needs JavaScript.)
The linear sieve on 1 to 50, one frame per that writes something.
The label under a composite is the only write it gets. Trace
from python3 -m cpmath.linear_sieve_trace 50 in cp-math.
Why each composite is written exactly once
Lemma. Let and let be a prime with . Then .
Proof. A prime dividing divides or (Euclid’s lemma for primes, lesson 4), so it is or a prime factor of , which is at least . So no prime factor of is below , and is one.
Theorem. After linear_sieve(n), lp[m] for
, and the inner loop writes each composite
exactly once, at and .
Primes are never written there.
Proof. By induction on , show that when the outer loop reaches
, lp[i] is 0 if is prime and if not.
Suppose that holds for every value up to . Then the first test appends
only primes to the list and sets lp[i] to for a prime
too. The inner loop writes lp[i * p] = p only for primes
, so by the lemma each write stores the right
value, the number written is composite, and it determines the pair:
, . So no entry is written twice, and no
prime is ever written.
Every composite is written. Let and
. No prime factor of is below , so
, and joined the list when the outer loop
was at . At , the inner loop runs through the primes in increasing
order; each passes both tests ( and
), and so does , so lp[m] = p is written, at step
.
That gives the induction step: a composite holds from step on, and a prime is still 0 when the loop reaches it.
So the inner loop writes exactly times, and each adds at most one more look at a prime, the one that stops it. That is fewer than steps in all: .
What linear time buys
Counted in a run, against lesson 5’s writes:
n = 10^6: composites 921501, linear sieve writes 921501, primes looked at 1921332, Eratosthenes writes 2122048
n = 10^7: composites 9335420, linear sieve writes 9335420, primes looked at 19334973, Eratosthenes writes 22850051
Counting every look, the linear sieve takes slightly fewer steps than
Eratosthenes makes writes. In Python each look is a trip round the
interpreter, while lesson 5’s bytearray sieve did its writes in C. One
run on an Apple M2 Pro, Python 3.15.2, read to one significant figure:
sieve(10**7): 0.790 s
sieve_flags(10**7): 0.013 s
linear_sieve(10**7): 0.834 s
The linear sieve was about as fast as the plain list sieve and some 60
times slower than the bytearray one. It also stores a Python int per
entry instead of a byte, and sys.getsizeof counts only the list’s
pointers, not the int objects they point to:
sys.getsizeof(lp) for 10**7 = 80000064, len(primes) = 664579, sys.getsizeof(primes) = 5933720
So in Python, use the bytearray sieve when only the primes are needed, and
the linear sieve when the smallest prime factors or a multiplicative
function are needed too.
In C++ (Apple clang 21, -O2), lesson 5’s vector<char> sieve against
the linear sieve with a vector<int> table, one run:
n = 10^7 eratosthenes (vector<char>): pi = 664579 0.02 s 10000001 bytes
n = 10^7 linear (vector<int> lp): pi = 664579 0.03 s 40000004 bytes for lp (+ 8388604 allocated as primes grew)
n = 10^8 eratosthenes (vector<char>): pi = 5761455 0.31 s 100000001 bytes
n = 10^8 linear (vector<int> lp): pi = 5761455 0.31 s 400000004 bytes for lp (+ 67108860 allocated as primes grew)
Reruns varied by up to 0.03 s, and neither sieve was ahead in all of them
at . The linear sieve’s time also includes
recording the largest product i * p at each look (the next section). Even
so, it matches what cp-algorithms reports: in practice about as fast as a
typical sieve of Eratosthenes. The cost is
memory, 4 bytes per entry against 1 (or an eighth of one, packed), so
does not fit a 256 MB limit.
Does i * p overflow?
The demo uses int and computes i * p before comparing it with .
The first look multiplies by 2, giving at most . Any later
follows a prime that passed, so , and by Bertrand’s
postulate (there is a prime between and for every ) the
next prime is . So : no product exceeds , which
fits in an int for . The demo records the largest
product, and its build with -fsanitize=undefined reported nothing:
n = 10^8 same primes: yes; largest i * p computed: 200000000 (2n = 200000000)
The order of the two tests does not change this: the loop reaches a prime only after the one before it passed both, so the bound covers every product it computes, the one that stops the loop included.
Multiplicative functions in the same pass
A function on the positive integers is multiplicative if and whenever . By the fundamental theorem of arithmetic (lesson 4), such an is fixed by its values on prime powers: .
Example: the number of divisors is multiplicative, and . Proof. By uniqueness of factorization, the divisors of are . For coprime and , no prime divides both, so a divisor of splits uniquely as , where collects the prime powers of at primes of , and the rest. Then and , and conversely every such product divides . So the divisors of are in one-to-one correspondence with pairs of divisors of and of .
The linear sieve knows, at each write , whether is new
to . If , then , so
and . If , it is one more factor of
a prime already has, and the sieve needs the whole power. It keeps
, the largest power of dividing , in the array
pk. Then with coprime to , and
:
def multiplicative(n, f_pk):
"""f[0..n] for the multiplicative function f with f(p**e) = f_pk(p, e)
(f[0] = 0, f[1] = 1 for n >= 1).
pk[m] is the largest power of lp(m) that divides m, so m = pk[m] * r
with r = m // pk[m] coprime to it, and f(m) = f(pk[m]) * f(r)."""
f = [0] * (n + 1)
lp = [0] * (n + 1)
pk = [0] * (n + 1)
e = [0] * (n + 1)
primes = []
if n >= 1:
f[1] = 1
for i in range(2, n + 1):
if lp[i] == 0:
lp[i] = pk[i] = i
e[i] = 1
f[i] = f_pk(i, 1)
primes.append(i)
for p in primes:
m = i * p
if p > lp[i] or m > n:
break
lp[m] = p
if p < lp[i]: # p does not divide i
pk[m], e[m] = p, 1
f[m] = f[i] * f[p]
else: # p = lp(i): one more factor p
pk[m], e[m] = pk[i] * p, e[i] + 1
f[m] = f[i // pk[i]] * f_pk(p, e[m])
return f
The value f[i // pk[i]] it reads is final. Each f[m] is written in the
same step as lp[m]: for a composite , at the outer loop’s step
(the theorem), for a prime at step , and
f[1] before the loop. So when the loop reaches , every f[m] with
is final, and . With f_pk = lambda p, e: e + 1 this is divisor_counts, and with
, the sum of , it is
divisor_sums; the sum of divisors is multiplicative by the same
correspondence of divisors.
For many functions the power is not needed, because the rule for
only looks at . The Möbius function
is 0 when a square above 1 divides , and when
is a product of distinct primes. If ,
then , so . Otherwise has one more prime
than , and is squarefree exactly when is, so .
In the repo’s mobius_sieve that is one line,
mu[i * p] = 0 if p == lp[i] else -mu[i].
Euler’s counts the from 1 to with . Among , exactly the multiples of share a factor with , so . That is multiplicative is proved in the lesson on the totient; here it is assumed, and the tests check the result against a gcd count. From it: if , ; if and is the power of in , the factor becomes , which is times as large, so :
def phi_sieve(n):
"""phi(m), the count of 1 <= k <= m with gcd(k, m) = 1, for
0 <= m <= n (phi[0] = 0)."""
phi = [0] * (n + 1)
lp = [0] * (n + 1)
primes = []
if n >= 1:
phi[1] = 1
for i in range(2, n + 1):
if lp[i] == 0:
lp[i] = i
phi[i] = i - 1
primes.append(i)
for p in primes:
if p > lp[i] or i * p > n:
break
lp[i * p] = p
phi[i * p] = phi[i] * p if p == lp[i] else phi[i] * (p - 1)
return phi
d(1..12) = [1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6]
mu(1..12) = [1, -1, -1, 0, -1, 1, -1, 0, 0, 1, -1, 0]
phi(1..12) = [1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4]
omega(1..12) = [0, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 2]
The last line is , the number of distinct prime factors (the
repo’s omega_sieve). It is not multiplicative but additive,
for coprime , and the same
pass computes it (exercise 4). In the timing run above, phi_sieve(10**6)
took 0.135 s and divisor_counts(10**6) 0.153 s.
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 1390. Four Divisors: and for every value up to from one pass; add for each with .
- LeetCode 2818. Apply Operations to Maximize Score: the prime score is , from
omega_sieveup to ; the rest is a monotonic stack (ties go to the smaller index) and taking the largest values first. - Codeforces 1512G. Short Task: for every from the linear sieve, then the smallest for each value up to , and for a value no reaches; since for , no larger can give a value in range, and gives .
- Codeforces 1499D. The Number of Pairs: for each divisor of , must be divisible by , and then the coprime ordered pairs with product number ; goes up to , so sieve that far.
- Codeforces 1717E. Madoka and The Best University: for each and each divisor of , the pairs with and number when , and none when ; up to from
phi_sieve.
Try it yourself
- In
linear_sieve(50), which and write 36, and which write 45? Which writes the most entries, and which are they? - For , how many primes does the inner loop look at in all, and how many of those looks write? Explain the difference.
- Given , and , use the sieve’s rules to get , and of and of .
- Prove the rule
omega_sieveuses: for and a prime , if and otherwise. - A number is perfect when . Which are perfect?
Answers
Each one is asserted in tests/test_lesson06.py, by brute force or by
running the sieve’s loop.
Show the answers
- and : is the smallest prime factor and . writes the most, four entries: 14, 21, 35 and 49, one for each prime up to . No other writes more than three.
- 169 looks, 74 of which write: one per composite up to 100. Each of the other 95 stops an . There are 99 values of ; the 4 primes with (2, 3, 5, 7) reach the end of the list of primes instead of stopping on a look.
- . For 90, : , , . For 135, : , ; for , , so and .
- The prime factors of are those of together with (Euclid’s lemma for primes). If , is already one of them; if , does not divide , so it is a new one.
- 6, 28, 496 and 8128.
Sources
- cp-algorithms, Linear Sieve: the algorithm with the
lpandprarrays, the proof that each composite is visited once through its representation with , and the remark that in practice it runs about as fast as a typical sieve of Eratosthenes while needing an array of numbers instead of bits. It names the algorithm a variant of Algorithm 3.3 in P. Pritchard, “Linear prime-number sieves: a family tree”, Science of Computer Programming 9 (1987), 17–35. - Wikipedia, Sieve of Eratosthenes, section “Euler’s sieve”: the version in which each composite is eliminated exactly once, and its linear-time rediscovery by D. Gries and J. Misra, “A linear sieve algorithm for finding prime numbers”, Communications of the ACM 21(12) (1978), 999–1003.
- Wikipedia, Multiplicative function: the definition, and the divisor function, and as examples.
- Wikipedia, Bertrand’s postulate: for every there is a prime with , proved by Chebyshev in 1852.
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.