Sub topic 13
Smallest Prime Factor Tables for Fast Factorization
This chapter assumes you already know how the sieve of Eratosthenes works, why each crossing-out pass starts at p squared, and what the fundamental theorem of arithmetic says. You should also be able to read Big-O notation. Here we change the sieve so that it records a small piece of extra information about every number. That extra information turns factorization from a search into a lookup.
The Problem: Factorizing Many Numbers
Trial division factorizes one number x in O(√x) time. That cost is fine for a single number. Suppose instead you need the prime factorization of a million numbers, all below ten million. Running trial division a million times means up to about 3,000 divisions each, or billions of operations in total.
The usual sieve gives a yes-or-no answer for each number: prime or not. When it crosses out a composite number, it throws away the most useful fact it had at that moment, which is the prime that crossed the number out. If the sieve keeps that prime, factorization becomes cheap.
What a Smallest Prime Factor Table Is
A smallest prime factor table, or SPF table, is an array spf where spf[x] holds the smallest prime that divides x, for every x from 2 to n. For a prime x, spf[x] = x.
| x | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 12 | 15 | 21 | 49 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| spf[x] | 2 | 3 | 2 | 5 | 2 | 7 | 2 | 3 | 2 | 2 | 3 | 3 | 7 |
The table answers "what is one prime factor of x?" in constant time. Repeating that question on what remains gives the full factorization.
Building the Table with a Modified Sieve
The construction follows the sieve of Eratosthenes. The difference is that crossing out a number writes the current prime into its slot instead of writing False.
def smallest_prime_factors(n):
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
def factorize(x, spf):
factors = []
while x > 1:
factors.append(spf[x])
x //= spf[x]
return factors
spf = smallest_prime_factors(100)
print(factorize(84, spf)) # [2, 2, 3, 7]The code makes three choices that need explaining.
- Initialization to
spf[x] = x. Every number starts out claiming to be its own smallest prime factor. Numbers that never get overwritten are prime, sospf[p] == pplays the same role asis_prime[p]in the plain sieve. - The guard
if spf[m] == m. The passes run with increasing p, so the first prime to reach m is the smallest prime dividing m. The guard stops later, larger primes from overwriting that value. - Starting at
p * p. This is still correct. If m is composite and its smallest prime factor is p, then m = p · k where every prime factor of k is at least p. So k ≥ p and m ≥ p². The pass for p therefore always reaches m, and no composite number is missed.
Factorizing by Repeated Division
The factorize function uses the fundamental theorem of arithmetic directly. Look up the smallest prime factor of x, record it, divide it out, and repeat on the quotient. The quotient is always smaller than x and still at most n, so its entry is always in the table.
Here is the trace for x = 84:
| Step | x | spf[x] | factors so far | x // spf[x] |
|---|---|---|---|---|
| 1 | 84 | 2 | [2] | 42 |
| 2 | 42 | 2 | [2, 2] | 21 |
| 3 | 21 | 3 | [2, 2, 3] | 7 |
| 4 | 7 | 7 | [2, 2, 3, 7] | 1 |
The factors come out in non-decreasing order with no extra sorting. After you divide out a factor p, the quotient has no prime factor smaller than p.
Why Each Query Is O(log x)
Every loop iteration divides x by a prime, and every prime is at least 2. After k iterations x has shrunk by a factor of at least 2^k, so the loop runs at most log₂ x times. The worst case is a power of two: 2^23 = 8,388,608 needs 23 lookups. Trial division of the same number could need up to √x ≈ 2,900 divisions when x is prime. More typical numbers have far fewer factors, around ln ln x on average, so most queries finish in a handful of steps.
Common Variations
Prime and Exponent Pairs
Many problems need the factorization as (prime, exponent) pairs, for example 84 = 2² · 3 · 7. Factors arrive in sorted order, so equal primes are next to each other and you can group them in one pass. From the pairs you can compute the number of divisors, which is the product of (e + 1) over all pairs.
def smallest_prime_factors(n):
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
def factorize_pairs(x, spf):
pairs = []
while x > 1:
p = spf[x]
e = 0
while x % p == 0:
x //= p
e += 1
pairs.append((p, e))
return pairs
def divisor_count(x, spf):
count = 1
for _, e in factorize_pairs(x, spf):
count *= e + 1
return count
spf = smallest_prime_factors(1000)
print(factorize_pairs(360, spf)) # [(2, 3), (3, 2), (5, 1)]
print(divisor_count(360, spf)) # 24The same pattern gives the number of distinct prime factors (len(pairs)), the sum of divisors, and Euler's totient φ(x) = x · ∏(1 − 1/p).
The Linear Sieve
The Eratosthenes-style build costs O(n log log n), because a composite such as 30 is visited once by each of its prime factors up to √n. A linear sieve visits each composite exactly once, at the moment it is written as i · p, where p is its smallest prime factor. The result is O(n) time, and you get a list of the primes along the way.
def linear_sieve(n):
spf = [0] * (n + 1)
primes = []
for i in range(2, n + 1):
if spf[i] == 0:
spf[i] = i
primes.append(i)
for p in primes:
if p > spf[i] or i * p > n:
break
spf[i * p] = p
return spf, primes
spf, primes = linear_sieve(50)
print(primes) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
print(spf[45], spf[49]) # 3 7The condition p > spf[i] keeps the sieve linear. Once p is larger than the smallest prime factor of i, the product i · p has a smaller prime factor than p, so it will be marked later from a different i. In pure Python the linear sieve is often no faster in wall-clock time. Its inner loop runs interpreted Python for every composite, while the Eratosthenes version spends its time in tight range loops. The asymptotic gain shows up clearly in compiled languages.
Costs and Limits
The SPF table pays for its speed with memory, and the price is higher than for a boolean sieve.
| Approach | Build cost | Per-query cost | Memory | Works for x above n? |
|---|---|---|---|---|
| Trial division | none | O(√x) | O(1) | yes |
| SPF table (Eratosthenes build) | O(n log log n) | O(log x) | O(n) integers | no |
| SPF table (linear build) | O(n) | O(log x) | O(n) integers plus prime list | no |
Each entry has to hold a whole number, not a single bit. A packed 32-bit array takes 4 bytes per entry, so n = 10⁷ needs about 40 MB. A Python list is much heavier. Each slot is an 8-byte pointer, and list(range(n + 1)) creates a separate integer object of about 28 bytes for every value above 256. That comes to several hundred megabytes for n = 10⁷.
Watch for these failure modes:
- Queries beyond n.
spf[x]raisesIndexErrorfor x > n. To handle a larger x, divide out small primes using the table until the quotient fits, or fall back to trial division. - x equal to 0 or 1. The loop returns an empty list for 1, which is correct because 1 has no prime factors. For 0 it also returns an empty list, which is wrong. Reject 0, and negative inputs, at the boundary.
- One-off queries. If you only factorize a few numbers, building a table of size n costs more than the trial divisions you save. The table pays off when the number of queries is large compared to √n.
When to Reach for an SPF Table
Use an SPF table when you need factorizations of many integers that all lie below a bound known in advance, and you can afford one integer of memory per number up to that bound. Typical cases include computing a multiplicative function such as φ, divisor counts, or the Möbius function for every number up to n, answering many "factorize x" queries in competitive programming, and grouping numbers by their prime factors. For a single large number, or numbers with no fixed upper bound, use trial division or a dedicated factorization algorithm instead.
Exercise
Using an SPF table built for n = 1000, trace factorize(360). List each value of x, the spf[x] looked up, and the final factor list.
Show answer
x = 360, spf = 2 → 180; x = 180, spf = 2 → 90; x = 90, spf = 2 → 45; x = 45, spf = 3 → 15; x = 15, spf = 3 → 5; x = 5, spf = 5 → 1. The factor list is [2, 2, 2, 3, 3, 5], which is 2³ · 3² · 5.
Exercise
Someone removes the if spf[m] == m guard from smallestprimefactors(100). What value does spf[30] hold, and does factorize(30, spf) still return the correct prime factors?
Show answer
The passes for p = 2, 3, 5 each overwrite slot 30, so spf[30] ends up as 5. Factorization still works: 30 → 5 leaves 6, then spf[6] is 3 (overwritten by the pass for 3) leaves 2, then 2 leaves 1. The output is [5, 3, 2], which has the correct primes but is no longer sorted. Code that relies on spf[x] being the smallest prime, or on equal primes appearing next to each other, breaks.
Exercise
What is the maximum number of loop iterations factorize can take for any x up to 10**6, and which x reaches it?
Show answer
Each iteration divides x by at least 2, so the count is at most floor(log2(106)) = 19. The value 219 = 524288 reaches it with exactly 19 iterations.
Exercise
Why is it safe for the SPF sieve to start each pass at p * p, even though spf must be filled in for every composite number?
Show answer
If p is the smallest prime factor of a composite m, then m = p · k, and every prime factor of k is at least p, so k ≥ p and m ≥ p². The pass for p therefore reaches m, and because smaller primes do not divide m, that pass is the first one to write spf[m].