man number-theory/spf-sieve
lesson 7 of 27 · Primes and factorization
Smallest-prime-factor sieve
Factor numbers, each up to . Lesson 4’s trial division did it in 0.9 s in Python when the numbers were random. When all of them are the prime 9999991, each one costs 1,581 trial divisors, and the same loop takes 6.5 s. A table that holds, for every , its smallest prime factor turns each factorization into a handful of lookups: building the table and answering the queries took 0.3 to 0.4 s on either input. This lesson builds that table, proves that factoring with it takes at most divisions, and measures what it costs in time and memory.
The code is in cp-math at tag lesson-07,
in cpmath/spf.py. Its tests check both tables against brute force for
every up to 300 and against lesson 6’s linear sieve up to , and
compare factorize_spf with lesson 4’s factorize for every
and for 2,000 random . python3 -m cpmath.lesson07 prints
every Python output on this page (--time adds the timings). The C++
output comes from demos/spf.cpp.
The table
Write for the smallest prime factor of .
Lesson 6’s linear sieve already computes it, in its lp array. The sieve
of Eratosthenes computes it too, with one change: keep the first prime that
crosses each number out.
def spf_sieve(n):
"""spf[m] = the smallest prime factor of m for 2 <= m <= n, as a list
(spf[0] = 0, spf[1] = 1). The sieve of Eratosthenes, recording the
first prime that crosses each number out."""
spf = list(range(n + 1))
p = 2
while p * p <= n:
if spf[p] == p:
for m in range(p * p, n + 1, p):
if spf[m] == m:
spf[m] = p
p += 1
return spf
spf[m] == m plays the part of “not crossed out yet”. Lesson 5’s proof
showed that a composite is crossed out by its smallest prime
factor, and no prime smaller than that divides . The primes are taken
in increasing order, so the first prime to reach is
, and the test keeps later primes from overwriting it.
A prime is never crossed out and keeps spf[m] = m. The tests confirm
that, from 2 to , this table and the linear sieve’s are equal.
Building the smallest-prime-factor table for 1 to 100: p = 2 writes 2 into its 49 multiples from 4; p = 3 writes 3 into 16 of its multiples from 9 and leaves the 15 that already hold 2; p = 5 writes into 6, p = 7 into 3 (49, 77 and 91). Then 90 is factored with the table: spf[90] = 2 leaves 45, spf[45] = 3 leaves 15, spf[15] = 3 leaves 5, spf[5] = 5 leaves 1, so 90 = 2 · 3 · 3 · 5 in four divisions. (This figure steps through a recorded run; it needs JavaScript.)
Building the table for 1 to 100, one frame per prime, then factoring 90 by
following it. The label under a composite is its smallest prime factor;
an unlabelled number other than 1 is prime. Trace from
python3 -m cpmath.spf_trace 100 90 in cp-math.
Factoring with the table
To factor , divide by and repeat on what is left:
def factorize_spf(x, spf):
"""The factorization of x as a list of (p, e), p increasing, for
1 <= x < len(spf): divide by spf[x] until x is 1. That is one division
per prime factor counted with multiplicity, at most log2(x)."""
factors = []
while x > 1:
p = spf[x]
x //= p
if factors and factors[-1][0] == p:
factors[-1] = (p, factors[-1][1] + 1)
else:
factors.append((p, 1))
return factors
Theorem. For below the table’s length, factorize_spf
returns the prime factorization of with the primes in increasing
order, after exactly divisions, where
is the number of prime factors of counted with
multiplicity.
Proof. Each step divides the current value by the prime , so the primes divided out multiply to : they are its factorization, which is unique (lesson 4). They come in nondecreasing order: every prime factor of is a prime factor of , so . So equal primes are divided out one after another, and the grouping into pairs is right. There is one division per prime factor, in all, and since each prime is at least 2, .
factorize_spf(720720) = [(2, 4), (3, 2), (5, 1), (7, 1), (11, 1), (13, 1)]
factorize_spf(999983) = [(999983, 1)]
factorize_spf(524288) = [(2, 19)]
most divisions for x <= 10^6: 19, at x = 524288
most divisions for x <= 10^7: 23, at x = 8388608
The worst cases are the powers of 2, and ; a prime takes
one division. On average it is far fewer than the bound: factoring every
in the C++ demo took 3.92 divisions per number. The repo also
has distinct_primes_spf and count_divisors_spf, which walk the table the
same way. The number of divisors comes from the exponents, as in lesson 6:
.
Building it fast in Python
spf_sieve runs every test and write in Python’s loop: 1.2 s for
in the timing run below. Lesson 5’s bytearray trick does not
apply directly, because a slice assignment cannot skip the entries that
already hold a smaller prime. Turning the order around fixes that: let the
primes write from the largest down, so that the smallest prime writes last
and its value is the one that stays.
def spf_table(n):
"""spf_sieve(n) as an array of 4-byte unsigned ints, filled by slice
assignments: the primes p <= sqrt(n), largest first, each write p over
all their multiples from p*p on, so the smallest one writes last."""
spf = array("I", range(n + 1))
for p in reversed(primes_up_to(isqrt(n))):
spf[p * p::p] = array("I", [p]) * len(range(p * p, n + 1, p))
return spf
Why it is right. Prime writes exactly when and . The last writer is the smallest such prime. For a composite , is one of them, since (lesson 4), and no smaller prime divides ; so ends with . A prime is never written, since the only prime dividing it is itself and .
It does as many writes as lesson 5’s sieve, but in C. The array type
also stores numbers, not pointers: I is an unsigned C int, 4 bytes here
(the documentation promises at least 2), which holds values up to
4294967295. One run on an Apple M2 Pro, Python 3.15.2:
spf_sieve(10**7): 1.209 s
spf_table(10**7): 0.252 s
linear_sieve(10**7): 0.845 s
sys.getsizeof(spf_sieve(10**7)) = 80000072
sys.getsizeof(spf_table(10**7)) = 40970224
As in the earlier lessons, these are single runs, good to one significant
figure. The list’s size counts only its pointers, not the int objects
they point to.
When the table pays
The table costs its build time and entries of memory before it answers anything, so it pays when there are many numbers to factor. From the same run, with the queries drawn from a fixed seed:
factorize_spf on every x <= 10**6: 1.20 s
factorize (lesson 4) on every x <= 10**6: 3.89 s
10**5 random x <= 10**7: spf_table(10**7) and factorize_spf 0.32 s, factorize 0.90 s
10**5 times x = 9999991: spf_table(10**7) and factorize_spf 0.39 s, factorize 6.46 s
On random inputs, trial division was only about three times slower. What makes it slow is a large prime, or a product of two primes near (lesson 4), and a problem’s tests can be made of them. The table’s build cost depends only on the largest input, and each query then costs at most divisions. So the rule of thumb: many numbers up to about , build the table; a few numbers, or numbers beyond what a table can hold, use trial division (lesson 4) or, later in the course, Miller–Rabin and Pollard’s rho.
In C++: a 16-bit table
A composite has (lesson 4), so up to
every composite’s entry is below and fits in a
uint16_t. A prime’s own value need not fit (no prime above 65535 does), so the
16-bit table stores 0
for a prime and the lookup reads 0 as “the number itself”:
// The same in 16 bits: 0 for a prime, else its smallest prime factor,
// which is at most sqrt(n) < 65536 for n < 2^32.
std::vector<std::uint16_t> spf_u16(int n) {
std::vector<std::uint16_t> spf(n + 1, 0);
for (int i = 2; i <= n / i; i++)
if (spf[i] == 0)
for (int j = i * i; j <= n; j += i)
if (spf[j] == 0) spf[j] = (std::uint16_t)i;
return spf;
}
The outer loop stops at i <= n / i, so i * i cannot overflow (lesson 5).
The demo builds both tables up to , factors every number with each,
and checks that the factors agree (Apple clang 21, -O2, one run; three
earlier runs were within 0.1 s of it):
spf table to 10^8: int 400000004 bytes, 0.65 s; uint16_t 200000002 bytes, 0.46 s
factored every x <= 10^8 in 1.84 s: 392351272 divisions in all, 3.92 per number
most divisions: 26, first at x = 67108864; largest spf of a composite: 9973
uint16_t table gives the same factors: yes (392351272 divisions)
The largest smallest prime factor of a composite up to is 9973, the
largest prime whose square is at most , well inside 16 bits. The two
build times are not like for like: the int version’s outer loop runs to
to store each prime as its own factor, while the 16-bit one stops at
. Half the memory matters at the limits. At , by the same 2 and 4 bytes per
entry (the demo only ran ), that is 20 MB instead of 40 MB; at
even the 16-bit table, 200 MB, leaves little of a 256 MB limit.
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.
- Codeforces 1366D. Two Divisors: with , take the full power of in and ; when is a prime power, and the answer is .
- Codeforces 1176D. Recover it!: a composite’s largest proper divisor is , and the -th prime comes from the sieve’s list of primes up to 2750131; the largest remaining composite must be in , and once the composites are done, so must the smallest remaining prime.
- Codeforces 154B. Colliders: factor each with the table and keep, for each prime, which active collider uses it; collider 1 has no prime factor and never conflicts.
- LeetCode 2709. Greatest Common Divisor Traversal: union each index with its distinct prime factors; a 1 connects to nothing, so the answer is false when there is a 1 and more than one element.
- LeetCode 952. Largest Component Size by Common Factor: the same union over distinct prime factors, then count the largest group.
- LeetCode 1998. GCD Sort of an Array: union each value with its prime factors; sorting works exactly when every value and the value at its place in the sorted array are in the same group.
- LeetCode 2584. Split the Array to Make Coprime Products: record the last index of each prime factor; scanning from the left, the first where every prime seen so far ends by is the answer.
Try it yourself
- Which need the most divisions in
factorize_spf, and how many? - Suppose
spf_tabletook the primes in increasing order instead of decreasing. What wouldspf[30]end up as? How many entries from 2 to 100 would be wrong? - Prove that a composite has , and so that every composite below has its smallest prime factor below .
- Factor 720720 with the table and count its divisors.
- Which need 19 divisions? Why does none need 20?
Answers
Each one is asserted in tests/test_lesson07.py, by brute force or, for
the last one, with lesson 4’s trial division.
Show the answers
- 64 and 96, with 6 divisions each: and . Anything with 7 prime factors is at least .
- 5: the last prime to write 30 would be the largest prime with and . 25 entries would be wrong, the composites with a second prime factor with : 12, 18, 24, 30, 36, and so on to 100.
- Write with . Then , and ; being an integer, it is at most . For , .
- , so .
- 524288 and 786432 . Twenty prime factors make at least .
Sources
- cp-algorithms, Linear Sieve: the
lparray of minimum prime factors and its use to factor any number in the range in time proportional to the size of its factorization. - cp-algorithms, Sieve of Eratosthenes: the sieve this lesson’s table is built on.
- Wikipedia, Prime omega function: , the number of prime factors counted with multiplicity, and , the distinct ones.
- Python documentation, array: the type codes and their minimum sizes (
I: unsigned int, at least 2 bytes). - cppreference, Fixed width integer types:
std::uint16_t.
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.