man number-theory/trial-division
lesson 4 of 27 · Primes and factorization
Primality and factoring by trial division
Is prime? Dividing it by every smaller number takes two billion divisions. Dividing only up to its square root takes 46,339, and skipping even divisors after 2 brings that down to 23,170. The same loop factors any number, and it is fast or slow depending on the number’s factors, not its size: factors after 26,290 trial divisors, while the prime needs half a billion. This lesson proves why the square root is enough, shows the loop with a proof that it is right, and measures how far it goes in a time limit.
The code is in cp-math at tag lesson-04,
in cpmath/trial_division.py. Its tests compare every function with brute
force, and python3 -m cpmath.lesson04 prints every Python output on this
page (--time adds the timings). The C++ output comes from
demos/trial_division.cpp in the same repo.
Divisors come in pairs
A prime is an integer whose only positive divisors are 1 and . An integer that is not prime is composite. 1 is neither.
If divides , so does . The divisors of 36 pair up as , , , , : in each pair one number is at most and the other at least 6. That holds for every : if both and were larger than , their product would be larger than . Two facts follow.
Lemma 1. A composite has a divisor with .
Proof. Write with . Then , so .
Lemma 2. The smallest divisor of an integer is prime.
Proof. If had a divisor with , then would also divide , and it is smaller than .
Together: a composite has a prime factor at most . So to test , it is enough to try every with .
Testing one number
def is_prime(n):
"""True when n is prime: trial division by 2, then by odd d with
d*d <= n."""
if n < 2:
return False
if n % 2 == 0:
return n == 2
d = 3
while d * d <= n:
if n % d == 0:
return False
d += 2
return True
The condition is d * d <= n, not d <= math.sqrt(n): lesson 2 showed the
float square root going wrong from about on. In Python
the product is exact; in C++ it can overflow, as a later section shows. Once
2 is handled, even cannot divide an odd , so only odd are
tried. For a prime that is one division for 2 and then one for each
odd from 3 to , about :
10^9: largest prime below is 999999937; is_prime does 15811 divisions
10^10: largest prime below is 9999999967; is_prime does 50000 divisions
10^12: largest prime below is 999999999989; is_prime does 500000 divisions
10^14: largest prime below is 99999999999973; is_prime does 5000000 divisions
10^16: largest prime below is 9999999999999937; is_prime does 50000000 divisions
The primes themselves come from the C++ demo, which searched down from each power of ten; the Python timing run below confirms that each is prime.
The 6k ± 1 wheel
Skipping multiples of 3 as well saves another third. Every integer is with . For it is even and for it is a multiple of 3, so every prime above 3 is or . After 2 and 3, it is enough to try the pairs , , , …:
def is_prime_wheel(n):
"""is_prime, dividing only by 2, 3 and the numbers 6k - 1, 6k + 1:
every prime above 3 has that form."""
if n < 4:
return n >= 2
if n % 2 == 0 or n % 3 == 0:
return False
d = 5
while d * d <= n:
if n % d == 0 or n % (d + 2) == 0:
return False
d += 6
return True
It can try slightly past ; that is harmless, since any divisor strictly between 1 and proves composite, and whenever and . The same idea with more small primes (a wheel of 30 or 210) saves less each time: the fraction of numbers left after removing multiples of 2, 3 and 5 is , against for 2 and 3.
Factoring
To factor , divide out each as many times as it goes, and stop when for what is left of :
def factorize(n):
"""The prime factorization of n >= 1 as a list of (p, e), p increasing.
Invariant: when d is tried, n has no prime factor below d. So a d that
divides n is prime, and once d*d > n what is left of n is 1 or prime.
"""
factors = []
d = 2
while d * d <= n:
if n % d == 0:
e = 0
while n % d == 0:
n //= d
e += 1
factors.append((d, e))
d += 1 if d == 2 else 2
if n > 1:
factors.append((n, 1))
return factors
Why it is correct. Call what is left of . The loop tries 2 and then every odd number, so every prime below the current has been tried, and each one tried was divided out of completely. So when is tried, has no prime factor below . Three consequences:
- A that divides is prime: its smallest prime factor divides , so it is at least , so it is itself.
- A composite never divides , so trying it costs one division and nothing else.
- When the loop stops, . If were composite, Lemmas 1 and 2 would give it a prime factor at most , which it does not have. So is 1 or a prime, and that prime is larger than every factor found before it.
The figure steps through :
Factoring 8730 by trial division. d = 2 divides once, leaving 4365; d = 3 divides twice, leaving 485; d = 5 once, leaving 97; d = 7 and d = 9 do not divide 97; at d = 11, 121 is more than 97, so 97 is prime. (This figure steps through a recorded run; it needs JavaScript.)
Factoring 8730 by trial division, one frame per . Trace from python3 -m cpmath.factor_trace 8730 in cp-math.
Dividing out small factors shrinks , and the bound shrinks with it. That is why is quick and a prime of the same size is not:
factorize(10**18 - 1) = [(3, 4), (7, 1), (11, 1), (13, 1), (19, 1), (37, 1), (52579, 1), (333667, 1)]
the loop tried 26290 values of d and stopped at d = 52581 with n = 333667
The loop runs until passes the square root of what is left, so the slow inputs are those where what is left stays large: a prime, or a product of two primes near .
The fundamental theorem of arithmetic
The loop shows that every is a product of primes. That this product is unique, up to the order of the factors, is the fundamental theorem of arithmetic, and it needs one more fact.
Euclid’s lemma for primes. If a prime divides , then or .
Proof. If , then , since the only positive divisors of are 1 and . By Euclid’s lemma from lesson 1, and give .
By induction it extends to products of many factors: if divides , it divides one of the . Uniqueness: suppose some number had two different factorizations, and take the smallest, . The prime divides the right side, so it divides some , and since is prime, . Cancelling it gives two different factorizations of a smaller number, a contradiction.
So “the” factorization is well defined, and the exponents can be read off it. Two limits are worth knowing for 64-bit inputs: a number up to has at most 15 distinct prime factors, and at most 59 counted with multiplicity:
product of the first 15 primes = 614889782588491410 <= 10**18 < product of the first 16
largest e with 2**e <= 10**18: 59
How far it goes in a time limit
One recorded run on an Apple M2 Pro, best of three. In Python 3.15.2, testing the primes from the table above:
10^9: is_prime 0.0006 s, is_prime_wheel 0.0003 s (is_prime(999999937) = True)
10^10: is_prime 0.0026 s, is_prime_wheel 0.0013 s (is_prime(9999999967) = True)
10^12: is_prime 0.0278 s, is_prime_wheel 0.0140 s (is_prime(999999999989) = True)
10^14: is_prime 0.2789 s, is_prime_wheel 0.1400 s (is_prime(99999999999973) = True)
10^16: is_prime 2.7868 s, is_prime_wheel 1.4396 s (is_prime(9999999999999937) = True)
The wheel does a third fewer divisions and goes round its loop a third as
often; here it ran twice as fast. In C++ (Apple clang 21, -O2),
searching down from each power of ten for the largest prime (the time
includes the composites tried on the way):
largest prime below 10^14: 99999999999973 (search 0.008 s)
largest prime below 10^15: 999999999999989 (search 0.019 s)
largest prime below 10^16: 9999999999999937 (search 0.108 s)
largest prime below 10^17: 99999999999999997 (search 0.185 s)
largest prime below 10^18: 999999999999999989 (search 0.583 s)
999999866000004473 = 999999937 * 999999929: is_prime = 0 after 0.581 s (found the factor 999999929)
So on this machine, one test or factorization costs under a second up to about in Python and up to in C++. A judge may be slower, and many problems ask for numbers, not one. For those, the coming lessons replace trial division: sieves for many numbers below a limit, and the Miller–Rabin test for single numbers up to .
The overflow in d * d <= n
The usual C++ loop for int inputs has a bug at the top of the range:
// The common bug: for n near INT_MAX, d * d overflows before it exceeds n.
bool is_prime_overflowing(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; d++)
if (n % d == 0) return false;
return true;
}
For a prime , the loop reaches ,
and does not fit in an int. Signed overflow is
undefined behaviour. Built with -fsanitize=undefined:
demos/trial_division.cpp:16:23: runtime error: signed integer overflow: 46341 * 46341 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior demos/trial_division.cpp:16:23
is_prime(2147483647) = 1
is_prime_overflowing(2147483647) = 0
That build ran for 11 seconds before printing its wrong answer; the -O2
build printed the same wrong answer at once. Neither is guaranteed. The fix
is to compare by division, which cannot overflow:
// Compare by division instead: d <= n / d never overflows.
bool is_prime(long long n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
for (long long d = 3; d <= n / d; d += 2)
if (n % d == 0) return false;
return true;
}
For integers, holds exactly when .
Dividing by primes only
The composite the loop tries are wasted divisions (consequence 2 above). With many numbers to factor, find the primes up to the square root of the largest once, then divide only by those:
def factorize_with_primes(n, primes):
"""factorize(n), dividing only by primes: the list must hold every
prime up to some P >= isqrt(n), in increasing order."""
factors = []
for p in primes:
if p * p > n:
break
if n % p == 0:
e = 0
while n % p == 0:
n //= p
e += 1
factors.append((p, e))
else:
# every prime was tried, so n has no prime factor up to P = the
# last one; that makes it 1 or prime only if P >= isqrt(n), i.e.
# (P + 1)**2 > n
last = primes[-1] if primes else 1
if (last + 1) ** 2 <= n:
raise ValueError("not enough primes for this n")
if n > 1:
factors.append((n, 1))
return factors
primes up to 1000: 168 up to 10**6: 78498
p = 99999999977: isqrt = 316227; is_prime divides 158114 times, primes only: 27293 times
The list itself can come from trial division (primes_by_trial in the repo
builds the primes up to in 0.40 s in the run above); the next lesson’s
sieve does it much faster.
Listing divisors
The pairing of the first section lists all divisors in : the small one of each pair in increasing order, then the large ones in reverse.
def divisors(n):
"""All divisors of n >= 1, increasing. Each d <= sqrt(n) pairs with
n // d >= sqrt(n), so the loop stops at sqrt(n)."""
small, large = [], []
d = 1
while d * d <= n:
if n % d == 0:
small.append(d)
if d * d != n:
large.append(n // d)
d += 1
return small + large[::-1]
divisors(36) = [1, 2, 3, 4, 6, 9, 12, 18, 36] pairs: [(1, 36), (2, 18), (3, 12), (4, 9), (6, 6)]
The d * d != n test keeps a square’s middle divisor from appearing twice.
Counting and summing divisors from the factorization, without listing them,
is a later lesson.
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 2614. Prime In Diagonal:
is_primeon each diagonal value. - LeetCode 263. Ugly Number: divide out 2, 3 and 5 completely and look at what is left.
- LeetCode 2521. Distinct Prime Factors of Product of Array: factor each element separately and collect the primes in a set; the product itself is never needed.
- LeetCode 2507. Smallest Value After Replacing With Sum of Prime Factors: repeat
factorize, summing , until the value stops changing. - LeetCode 1492. The kth Factor of n:
divisors, or count the small half and then the large half. - LeetCode 507. Perfect Number: sum the divisor pairs up to .
- Codeforces 26A. Almost Prime: count distinct prime factors with
factorize. - Codeforces 1474B. Different Divisors: the answer is a product of two primes, each found by testing upward with
is_prime. - Codeforces 1068B. LCM: takes every divisor of as a value, so count the divisors of in pairs.
- Codeforces 1203C. Common Divisors: the common divisors of an array are the divisors of its gcd (lesson 3); count them in pairs.
- Codeforces 230B. T-primes: exactly three divisors means the square of a prime; check with
isqrt(lesson 2), then test the root against a precomputed list of primes.
Try it yourself
- Factor 9991 by trial division. How many values of does
factorizetry, up to and including the first one that divides 9991? - Is 1000003 prime? How many divisions does
is_primedo on it? - What is the largest number of distinct prime factors of a number up to , and the smallest number that has that many?
- Prove: if has no prime factor with , then is a prime or a product of two primes.
- List the divisors of 360 using pairs. How many are there?
- For which does
is_prime_overflowingoverflow? How many such are there?
Answers
Each one is asserted in tests/test_lesson04.py, by brute force or a direct
check where that is possible.
Show the answers
- (it is ). The loop tries and the odd numbers 3 to 97: 49 values.
- Yes. , so
is_primedivides by 2 and by the 499 odd numbers from 3 to 999: 500 divisions. - 7, first reached by . Eight distinct primes multiply to at least .
- Every prime factor of is greater than . If had three prime factors counted with multiplicity, their product, which divides , would exceed . So there are at most two.
- , , , , , , , , , , , : 12 pairs, 24 divisors.
- Exactly when the loop reaches without finding a divisor, that is, for the primes from to . A composite in that range has a prime factor at most and returns before. There are 4085 such primes, from 2147395609 to 2147483647.
Sources
- Wikipedia, Trial division: the method and its cost.
- Wikipedia, Fundamental theorem of arithmetic: the statement (every integer above 1 is a prime or a product of primes, unique up to order) and the uniqueness proof by a smallest counterexample and Euclid’s lemma.
- cp-algorithms, Integer factorization, sections “Trial division”, “Wheel factorization” and “Precomputed primes”.
- Euclid, Elements, Book VII, Proposition 30, in D. E. Joyce’s online edition: a prime dividing a product divides one of the factors.
- cppreference, Arithmetic operators: signed overflow is undefined behaviour.
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 plannedCrossing 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 plannedEach composite crossed out exactly once, by its smallest prime factor, with multiplicative functions computed in the same pass.
- 07 Smallest-prime-factor sieve plannedStore 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.