Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Primes: sieves, Miller–Rabin and factorisation

ProblemList the primes up to a bound or in a window, decide whether a 64-bit number is prime, and factor it completely
Devised byEratosthenes (c. 240 BC), the sieve; Gary Miller (1976) and Michael Rabin (1980), the strong probable-prime test; John Pollard (1975), the rho method; Richard Brent (1980), its faster cycle detection
AccuracyDeterministic and exact for every u64: the twelve Miller–Rabin bases have no common strong pseudoprime below ; agrees with SymPy on all reference cases
CostSieve time and bytes; segmented sieve memory for a window of width below ; Miller–Rabin twelve modular powers; Pollard’s rho about steps for the smallest factor
Read firstDivisibility and modular arithmetic
APIsieve_of_eratosthenes, segmented_sieve, prime_count, is_prime, is_strong_probable_prime, next_prime, pow_mod, factorize, pollard_rho, euler_totient, divisors

Overview

Three questions about primes need three different methods. To list all primes up to , the sieve of Eratosthenes crosses out multiples and keeps what survives, in nearly linear time. A segmented sieve does the same for a window far out, such as near , without sieving everything below it. To test one large number, Miller–Rabin checks a property every prime has and almost no composite shares. With the right twelve bases, no 64-bit composite passes them all. To factor, trial division removes small primes, and Pollard’s rho finds a factor of what remains in about steps, using the birthday paradox in the residues modulo .

Where it is used

Primes are the raw material of modern cryptography.

  • Public-key cryptography. RSA keys are products of two large primes found with a primality test such as Miller-Rabin; the security rests on factoring being hard.
  • Hashing and random numbers. Hash tables use prime sizes, and generators use prime moduli.
  • Mathematical research. Sieves generate the primes used in number-theory experiments.
  • Factoring. Cracking small keys and decomposing integers appear in puzzles and in the analysis of algorithms.

History

Eratosthenes of Cyrene described the sieve around 240 BC. Fermat’s little theorem (1640) gave the first fast compositeness test, but Carmichael numbers (Robert Carmichael, 1910) fool it for every base coprime to them. Gary Miller (1976) strengthened the test and proved it deterministic assuming the generalised Riemann hypothesis. Michael Rabin (1980) made it a randomised test with error at most per base. Gerhard Jaeschke and later Jonathan Sorenson and Jonathan Webster (2015) found the smallest numbers fooling the first prime bases, which makes it deterministic for bounded inputs. John Pollard’s rho method (1975) and Richard Brent’s improvement (1980) factored the eighth Fermat number in 1980. They remain the method of choice for factors up to about .

The idea

Sieves

To list all the primes up to , the sieve of Eratosthenes works by elimination. Write down the numbers from 2 to . The first, 2, is prime; cross out all its other multiples. The next number not crossed out, 3, is prime; cross out its multiples. Continue. A number that is never crossed out has no smaller prime factor, so it is prime.

Two refinements save work. A composite number has a prime factor at most , so only the primes need be used. And the crossing out for can begin at , because smaller multiples of have a smaller prime factor and are already crossed out. The total work is about operations, almost linear.

The library stores only odd numbers, one bit each, so needs 62 MB. When only the primes in a window are wanted, a segmented sieve first sieves the base primes up to , then crosses their multiples off just the window, using memory proportional to the window. The prime-counting function , the number of primes up to , follows by counting. By the prime number theorem it is approximately , and better approximated by the logarithmic integral :

Figure 22.2. Prime counting.

nπ(n)sieve of Eratosthenes (ms)primes in [n − 10⁶, n]segmented sieve of that window (ms)
10^6784981784981.5
10^766457912620901.5
10^85761455121543321.5
10^9508475341954479571.8

Miller–Rabin

A sieve is no use for testing whether one large number is prime. Primality tests rely instead on properties that every prime has and most composites lack.

Fermat’s test. By Fermat’s little theorem, if is prime then for every not divisible by . The power is cheap to compute by square-and-multiply. If the result is not 1, is certainly composite. Unfortunately the converse fails: some composites pass, and a few (the Carmichael numbers, such as ) pass for every base coprime to them.

The stronger test. Miller and Rabin add a second property of primes: modulo a prime, the only square roots of 1 are . Write with odd. Then is obtained from by squaring times, and the test examines the whole chain

If is prime the chain ends in 1, and the last entry before the 1s begin, being a square root of 1, must be . So for a prime, either already, or for some . A number that violates this is composite. For and , and the chain is : it reaches 1 from 67, which is not , so 561 is exposed although it passes Fermat’s test.

A composite that passes for base is a strong pseudoprime to that base. At most a quarter of the bases fool any composite, and composites that fool many small bases are very rare:

Table 22.2. Strong pseudoprimes and the bases they fool.

nfactorsbases it passes as a strong probable primeis_prime
204723 · 892, 11false
1373653829 · 16572, 3, 17, 19, 29, 31false
253260012251 · 112512, 3, 5false
3215031751151 · 751 · 283512, 3, 5, 7, 19, 37false
21523028987476763 · 10627 · 299472, 3, 5, 7, 11, 23, 31, 37false
34747496603831303 · 16927 · 1575432, 3, 5, 7, 11, 13, 31false
34155007172832110670053 · 320101572, 3, 5, 7, 11, 13, 17, 19false
3825123056546413051149491 · 747451 · 342332112, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31false

The smallest number fooling all of the first twelve primes as bases is , so testing those twelve, after trial division, decides primality for every u64 with certainty.

Pollard’s rho

Knowing that a number is composite does not reveal its factors. Trial division finds a factor in about steps. Pollard’s rho method finds it in about steps, by a clever use of chance.

The idea. Suppose is an unknown prime factor of . Generate a sequence of pseudo-random numbers modulo by iterating . Now imagine the same sequence reduced modulo . It takes only possible values, so it must eventually repeat, and by the “birthday paradox” a repeat is expected after only about steps, far fewer than . Once a value repeats, the sequence cycles for ever: drawn on paper, it is a tail leading into a loop, the shape of the letter ρ.

Detecting the repeat without knowing . We cannot reduce modulo , since is what we are looking for. But if , then divides , and therefore is a multiple of : a factor of , found with Euclid’s algorithm.

Brent’s variant. Comparing all pairs would be too slow. Brent’s version compares each new value against one saved value, which is refreshed at distances that double (1, 2, 4, 8, … steps), and it multiplies many differences together before taking one gcd, since a gcd is much more expensive than a multiplication. Occasionally the gcd is itself, because repeats for several factors were collected in the same batch. The method then backs up and steps one at a time; if that fails too, it changes :

Figure 22.3. Pollard's rho.

factorize removes the primes below 50 by trial division, then repeatedly splits composites with Pollard’s rho and certifies the pieces with Miller–Rabin. The totient and the list of divisors follow from the factorisation.

Algorithm

Sieve of Eratosthenes up to , storing one bit for each odd number.

  1. Clear all the marks.
  2. For each odd with : if is unmarked, it is prime; mark up to . (The step is because the multiples in between are even, and are not stored.)
  3. The primes are 2 and the unmarked odd numbers.

The cost is about bit operations and bytes of memory.

Miller-Rabin test of .

  1. Divide by each of the first twelve primes. If one divides it, is prime only if it equals that prime.
  2. Write with odd.
  3. For each of the twelve primes as base : compute . If is or , this base passes. Otherwise square up to times; if it becomes , the base passes; if it becomes 1, or never reaches , then is composite.
  4. If every base passes, is prime.

Each base costs one modular power, multiplications.

Factorisation of .

  1. Divide out every prime below 50, recording each as often as it divides.
  2. Put what remains, if it is greater than 1, on a stack.
  3. While the stack is not empty: remove a number. If it passes the primality test, record it as a prime factor. Otherwise find a nontrivial factor by Pollard’s rho, and put and the number divided by back on the stack.
  4. Sort the prime factors.

Implementation

    let mut i = 1usize;
    while (2 * i + 1) * (2 * i + 1) <= n as usize {
        if composite[i / 64] >> (i % 64) & 1 == 0 {
            let p = 2 * i + 1;
            let mut j = (p * p) / 2;
            while j < count {
                composite[j / 64] |= 1 << (j % 64);
                j += p;
            }
        }
        i += 1;
    }
    let s = (n - 1).trailing_zeros();
    let d = (n - 1) >> s;
    let mut x = pow_mod(a, d, n);
    if x == 1 || x == n - 1 {
        return true;
    }
    for _ in 1..s {
        x = mul_mod(x, x, n);
        if x == n - 1 {
            return true;
        }
    }
    false
        let (mut y, mut r, mut q) = (2u64, 1u64, 1u64);
        let (mut x, mut ys, mut g) = (0, 0, 1);
        const BATCH: u64 = 128;
        while g == 1 {
            x = y;
            for _ in 0..r {
                y = f(y);
            }
            let mut k = 0;
            while k < r && g == 1 {
                ys = y;
                for _ in 0..BATCH.min(r - k) {
                    y = f(y);
                    q = mul_mod(q, x.abs_diff(y), n);
                }
                g = gcd(q, n);
                k += BATCH;
            }
            r *= 2;
        }
  • 64-bit products are formed in 128 bits (mul_mod).

In practice

//! Primes: sieves, deterministic Miller-Rabin, factorisation, totients and divisors.

use lib_jsl_number_theory::integer_factorization::{divisors, euler_totient, factorize};
use lib_jsl_number_theory::primality::{is_prime, is_strong_probable_prime, next_prime};
use lib_jsl_number_theory::prime_sieves::{prime_count, segmented_sieve, sieve_of_eratosthenes};

fn main() {
    println!("primes below 50: {:?}", sieve_of_eratosthenes(50));
    println!("π(10⁶) = {}", prime_count(1_000_000));
    println!("primes in [10¹², 10¹² + 100]: {:?}", segmented_sieve(1_000_000_000_000, 1_000_000_000_100));
    // 2047 = 23 · 89 fools the base-2 Miller-Rabin test but not base 3.
    println!("2047: base 2 says prime {}, base 3 says prime {}, is_prime {}", is_strong_probable_prime(2047, 2), is_strong_probable_prime(2047, 3), is_prime(2047));
    println!("largest 64-bit prime is_prime: {}; next prime after 10^18: {:?}", is_prime(18446744073709551557), next_prime(1_000_000_000_000_000_000));
    // 2^64 − 1 and a product of two 10-digit primes.
    for n in [u64::MAX, 1_000_000_007 * 1_000_000_009] {
        println!("{n} = {:?}", factorize(n));
    }
    println!("φ(360) = {}, divisors of 360: {:?}", euler_totient(360), divisors(360));
}
primes below 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
π(10⁶) = 78498
primes in [10¹², 10¹² + 100]: [1000000000039, 1000000000061, 1000000000063, 1000000000091]
2047: base 2 says prime true, base 3 says prime false, is_prime false
largest 64-bit prime is_prime: true; next prime after 10^18: Some(1000000000000000003)
18446744073709551615 = [(3, 1), (5, 1), (17, 1), (257, 1), (641, 1), (65537, 1), (6700417, 1)]
1000000016000000063 = [(1000000007, 1), (1000000009, 1)]
φ(360) = 96, divisors of 360: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60, 72, 90, 120, 180, 360]

Strengths

  • Deterministic primality and complete factorisation for every 64-bit integer, typically in microseconds to milliseconds.
  • Compact bit-set sieves, and windows far beyond memory.

Weaknesses

  • 64-bit only; larger numbers need the elliptic-curve method or the quadratic and number field sieves.
  • Pollard’s rho is slow for two factors near (about 65 000 steps); the sieve of all primes to takes seconds.

Exercises

  1. Show that the sieve may start crossing out multiples of at .
  2. Prove that are the only square roots of 1 modulo an odd prime, and derive the Miller–Rabin condition.
  3. Show that 561 is a Carmichael number but not a strong pseudoprime to base 2.
  4. Explain the expected steps of Pollard’s rho with the birthday paradox.
  5. Use the segmented sieve to count the primes between and , and compare with .
Hints and answers
  1. A composite number below has a smaller prime factor than , so it has already been crossed out when the smaller primes were processed; is the first multiple of not yet crossed out.
  2. If then , so or . For , if is prime the sequence ends at and each term is the square of the previous one, so either it starts at 1 or reaches before 1; this is the Miller-Rabin condition.
  3. and is divisible by , and , so for every coprime to 561 (Carmichael). With : , then , , . The sequence reaches from , a nontrivial square root of 1, so base 2 exposes 561 as composite.
  4. After steps the sequence has produced about values modulo the unknown prime ; by the birthday paradox two of them collide modulo (while still differing modulo ) after about steps.
  5. The count should be near ; the exact count differs by a few hundred.

Further reading

  • R. Crandall and C. Pomerance, Prime Numbers: A Computational Perspective, 2nd ed., Springer, 2005, chapters 3 and 5.
  • M. O. Rabin, “Probabilistic algorithm for testing primality”, Journal of Number Theory 12 (1980) 128–138.
  • J. M. Pollard, “A Monte Carlo method for factorization”, BIT 15 (1975) 331–334.
  • R. P. Brent, “An improved Monte Carlo factorization algorithm”, BIT 20 (1980) 176–184.
  • J. Sorenson and J. Webster, “Strong pseudoprimes to twelve prime bases”, Mathematics of Computation 86 (2017) 985–1003.