man number-theory/trial-division

lesson 4 of 27 · Primes and factorization

Primality and factoring by trial division

lib / Number theory for competitive programming 15 mindraft

checked against: proofs in the text, code tested with Python 3.15.2

code: toothywalrus/cp-math@lesson-04

Is 231−1=21474836472^{31} - 1 = 2147483647 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: 1018−110^{18} - 1 factors after 26,290 trial divisors, while the prime 1018−1110^{18} - 11 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 p>1p > 1 whose only positive divisors are 1 and pp. An integer n>1n > 1 that is not prime is composite. 1 is neither.

If dd divides nn, so does n/dn/d. The divisors of 36 pair up as 1⋅361 \cdot 36, 2⋅182 \cdot 18, 3⋅123 \cdot 12, 4⋅94 \cdot 9, 6⋅66 \cdot 6: in each pair one number is at most 36=6\sqrt{36} = 6 and the other at least 6. That holds for every nn: if both dd and n/dn/d were larger than n\sqrt n, their product would be larger than nn. Two facts follow.

Lemma 1. A composite nn has a divisor dd with 2≤d≤n2 \le d \le \sqrt n.

Proof. Write n=abn = ab with 1<a≤b<n1 < a \le b < n. Then a2≤ab=na^2 \le ab = n, so a≤na \le \sqrt n. ■\blacksquare

Lemma 2. The smallest divisor d≥2d \ge 2 of an integer n≥2n \ge 2 is prime.

Proof. If dd had a divisor cc with 1<c<d1 < c < d, then cc would also divide nn, and it is smaller than dd. ■\blacksquare

Together: a composite nn has a prime factor at most n\sqrt n. So to test nn, it is enough to try every dd with d2≤nd^2 \le n.

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 4.5⋅10154.5 \cdot 10^{15} on. In Python the product is exact; in C++ it can overflow, as a later section shows. Once 2 is handled, even dd cannot divide an odd nn, so only odd dd are tried. For a prime pp that is one division for 2 and then one for each odd dd from 3 to p\sqrt p, about p/2\sqrt p / 2:

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 6k+r6k + r with r∈{0,1,2,3,4,5}r \in \{0, 1, 2, 3, 4, 5\}. For r=0,2,4r = 0, 2, 4 it is even and for r=3r = 3 it is a multiple of 3, so every prime above 3 is 6k+16k + 1 or 6k+5=6(k+1)−16k + 5 = 6(k+1) - 1. After 2 and 3, it is enough to try the pairs 5,75, 7, 11,1311, 13, 17,1917, 19, …:

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 d+2d + 2 slightly past n\sqrt n; that is harmless, since any divisor strictly between 1 and nn proves nn composite, and d+2<nd + 2 < n whenever d2≤nd^2 \le n and d≥5d \ge 5. 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 8/308/30, against 2/62/6 for 2 and 3.

Factoring

To factor nn, divide out each dd as many times as it goes, and stop when d2>nd^2 > n for what is left of nn:

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 mm what is left of nn. The loop tries 2 and then every odd number, so every prime below the current dd has been tried, and each one tried was divided out of mm completely. So when dd is tried, mm has no prime factor below dd. Three consequences:

  1. A dd that divides mm is prime: its smallest prime factor divides mm, so it is at least dd, so it is dd itself.
  2. A composite dd never divides mm, so trying it costs one division and nothing else.
  3. When the loop stops, d2>md^2 > m. If m>1m > 1 were composite, Lemmas 1 and 2 would give it a prime factor at most m<d\sqrt m < d, which it does not have. So mm is 1 or a prime, and that prime is larger than every factor found before it. ■\blacksquare

The figure steps through 8730=2⋅32⋅5⋅978730 = 2 \cdot 3^2 \cdot 5 \cdot 97:

Factoring 8730 by trial division, one frame per dd. Trace from python3 -m cpmath.factor_trace 8730 in cp-math.

Dividing out small factors shrinks mm, and the bound d2≤md^2 \le m shrinks with it. That is why 1018−110^{18} - 1 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 dd 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 n\sqrt n.

The fundamental theorem of arithmetic

The loop shows that every n>1n > 1 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 pp divides abab, then p∣ap \mid a or p∣bp \mid b.

Proof. If p∤ap \nmid a, then gcd⁡(p,a)=1\gcd(p, a) = 1, since the only positive divisors of pp are 1 and pp. By Euclid’s lemma from lesson 1, p∣abp \mid ab and gcd⁡(p,a)=1\gcd(p, a) = 1 give p∣bp \mid b. ■\blacksquare

By induction it extends to products of many factors: if pp divides q1q2⋯qkq_1 q_2 \cdots q_k, it divides one of the qjq_j. Uniqueness: suppose some number had two different factorizations, and take the smallest, p1⋯pk=q1⋯qlp_1 \cdots p_k = q_1 \cdots q_l. The prime p1p_1 divides the right side, so it divides some qjq_j, and since qjq_j is prime, p1=qjp_1 = q_j. Cancelling it gives two different factorizations of a smaller number, a contradiction. ■\blacksquare

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 101810^{18} 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 101410^{14} in Python and up to 101810^{18} in C++. A judge may be slower, and many problems ask for 10510^5 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 101810^{18}.

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 n≥463402=2147395600n \ge 46340^2 = 2147395600, the loop reaches d=46341d = 46341, and 463412=214748828146341^2 = 2147488281 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, d≤⌊n/d⌋d \le \lfloor n/d \rfloor holds exactly when d2≤nd^2 \le n.

Dividing by primes only

The composite dd 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 10610^6 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 O(n)O(\sqrt n): 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.

Try it yourself

  1. Factor 9991 by trial division. How many values of dd does factorize try, up to and including the first one that divides 9991?
  2. Is 1000003 prime? How many divisions does is_prime do on it?
  3. What is the largest number of distinct prime factors of a number up to 10610^6, and the smallest number that has that many?
  4. Prove: if n>1n > 1 has no prime factor pp with p3≤np^3 \le n, then nn is a prime or a product of two primes.
  5. List the divisors of 360 using pairs. How many are there?
  6. For which nn does is_prime_overflowing overflow? How many such nn 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
  1. 9991=97⋅1039991 = 97 \cdot 103 (it is 1002−32100^2 - 3^2). The loop tries d=2d = 2 and the odd numbers 3 to 97: 49 values.
  2. Yes. ⌊1000003⌋=1000\lfloor \sqrt{1000003} \rfloor = 1000, so is_prime divides by 2 and by the 499 odd numbers from 3 to 999: 500 divisions.
  3. 7, first reached by 510510=2⋅3⋅5⋅7⋅11⋅13⋅17510510 = 2 \cdot 3 \cdot 5 \cdot 7 \cdot 11 \cdot 13 \cdot 17. Eight distinct primes multiply to at least 9699690>1069699690 > 10^6.
  4. Every prime factor of nn is greater than n1/3n^{1/3}. If nn had three prime factors counted with multiplicity, their product, which divides nn, would exceed n1/3⋅n1/3⋅n1/3=nn^{1/3} \cdot n^{1/3} \cdot n^{1/3} = n. So there are at most two.
  5. 1⋅3601 \cdot 360, 2⋅1802 \cdot 180, 3⋅1203 \cdot 120, 4⋅904 \cdot 90, 5⋅725 \cdot 72, 6⋅606 \cdot 60, 8⋅458 \cdot 45, 9⋅409 \cdot 40, 10⋅3610 \cdot 36, 12⋅3012 \cdot 30, 15⋅2415 \cdot 24, 18⋅2018 \cdot 20: 12 pairs, 24 divisors.
  6. Exactly when the loop reaches d=46341d = 46341 without finding a divisor, that is, for the primes from 463402=214739560046340^2 = 2147395600 to 231−12^{31} - 1. A composite nn in that range has a prime factor at most n<46341\sqrt n < 46341 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.