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. Earlier chapters covered all three. Here you will change the sieve slightly so that it records how to break each number down, and not only whether the number is prime.
From "Is It Prime?" to "What Divides It?"
A plain sieve stores one boolean per number. That is enough to list primes, but it cannot tell you the factors of 84. If you need to factorize many numbers, running trial division on each one costs up to O(√x) per number. With a million queries, that adds up.
A smallest prime factor table (SPF table) is an array where spf[x] holds the smallest prime that divides x. For a prime p, spf[p] == p. For 84, spf[84] == 2. With this table, factorizing x becomes a loop of table lookups and divisions.
Building the Table
The construction follows the sieve closely. Each entry starts as its own index, meaning "no smaller factor found yet." When the outer loop reaches a prime p, it walks through the multiples of p starting at p * p. It writes p into any entry that still holds its own index.
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 test spf[p] == p takes the place of the boolean is_prime[p] check. It holds exactly when no smaller prime has claimed p, which means p is prime.
Factorizing by Repeated Division
The factorize function relies on the fundamental theorem of arithmetic. If p = spf[x], then x = p * (x // p), and the rest of the factorization is the factorization of x // p. The function repeats this step until x reaches 1.
Each step divides x by at least 2, so the loop runs at most log₂(x) times. A query costs O(log x), compared with O(√x) for trial division.
If you want the result as prime powers, group the factors:
from collections import Counter
spf = smallest_prime_factors(1000)
print(Counter(factorize(360, spf))) # Counter({2: 3, 3: 2, 5: 1})Costs and When to Use It
| Approach | Setup | Per query | Memory | Valid range |
|---|---|---|---|---|
| Trial division | none | O(√x) | O(1) | any x |
| SPF table | O(n log log n) | O(log x) | O(n) integers | x ≤ n only |
Common mistakes:
- Querying beyond the table.
factorize(x, spf)withx > nraisesIndexError. Size the table for the largest value you expect. - Underestimating memory. The table stores one integer per entry, while a boolean sieve can use one bit per entry. In CPython a list of 10⁷ ints takes hundreds of megabytes. Use
array('i')or NumPy for largen. - Building it for one query. If you factorize only a few numbers, the setup cost is wasted. Use trial division.
The SPF table pays off when you have many factorization queries on numbers below a known bound. Competitive programming problems and precomputing divisor counts or Euler's totient over a range are typical cases.
Exercise
Using a table from smallestprimefactors(100), trace factorize(90, spf). List each value of x and the spf value read at each step, and give the final list.
Show answer
x = 90, spf = 2, x becomes 45. x = 45, spf = 3, x becomes 15. x = 15, spf = 3, x becomes 5. x = 5, spf = 5, x becomes 1. The result is [2, 3, 3, 5].
Exercise
Suppose the guard if spf[m] == m is removed from smallestprimefactors(100). What value ends up in spf[30], and why?
Show answer
spf[30] becomes 5. Primes 2, 3, and 5 all reach 30, since each starts at its square (4, 9, 25) and 30 is a multiple of each. Without the guard, the last prime to write wins, and that is 5, not the correct value 2. Prime 7 starts at 49 and never reaches 30.