Skip to main content

lib_jsl_number_theory/
primality.rs

1//! Deterministic primality testing for 64-bit integers.
2//!
3//! See the book entry [Primes: sieves, Miller–Rabin and factorisation](https://jwkunz.github.io/lib_jsl/book/number-theory/primes.html).
4
5/// `a · b mod m` without overflow.
6pub fn mul_mod(a: u64, b: u64, m: u64) -> u64 {
7    ((a as u128 * b as u128) % m as u128) as u64
8}
9
10/// `base^exponent mod m` by binary exponentiation (`m > 0`).
11pub fn pow_mod(mut base: u64, mut exponent: u64, m: u64) -> u64 {
12    let mut result = 1 % m;
13    base %= m;
14    while exponent > 0 {
15        if exponent & 1 == 1 {
16            result = mul_mod(result, base, m);
17        }
18        base = mul_mod(base, base, m);
19        exponent >>= 1;
20    }
21    result
22}
23
24/// Whether `n` passes the Miller-Rabin strong probable-prime test to base `a`.
25pub fn is_strong_probable_prime(n: u64, a: u64) -> bool {
26    if n < 2 {
27        return false;
28    }
29    if n.is_multiple_of(2) {
30        return n == 2;
31    }
32    let a = a % n;
33    if a == 0 {
34        return true;
35    }
36    // ANCHOR: miller_rabin
37    let s = (n - 1).trailing_zeros();
38    let d = (n - 1) >> s;
39    let mut x = pow_mod(a, d, n);
40    if x == 1 || x == n - 1 {
41        return true;
42    }
43    for _ in 1..s {
44        x = mul_mod(x, x, n);
45        if x == n - 1 {
46            return true;
47        }
48    }
49    false
50    // ANCHOR_END: miller_rabin
51}
52
53/// Deterministic primality for every `u64`: Miller-Rabin with the first twelve prime bases,
54/// whose smallest common strong pseudoprime is 318 665 857 834 031 151 167 461 ≈ 3.2 · 10²³
55/// (Sorenson and Webster, 2015), far above `u64::MAX` ≈ 1.8 · 10¹⁹, after trial division by
56/// small primes.
57pub fn is_prime(n: u64) -> bool {
58    const BASES: [u64; 12] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
59    if n < 2 {
60        return false;
61    }
62    for &p in &BASES {
63        if n.is_multiple_of(p) {
64            return n == p;
65        }
66    }
67    if n < 41 * 41 {
68        return true;
69    }
70    BASES.iter().all(|&a| is_strong_probable_prime(n, a))
71}
72
73/// The smallest prime `≥ n` (`None` past the largest 64-bit prime).
74pub fn next_prime(n: u64) -> Option<u64> {
75    (n.max(2)..=u64::MAX).find(|&k| is_prime(k))
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use crate::prime_sieves::sieve_of_eratosthenes;
82
83    #[test]
84    fn agrees_with_the_sieve_and_rejects_pseudoprimes() {
85        let primes: std::collections::HashSet<u64> = sieve_of_eratosthenes(100_000).into_iter().collect();
86        assert!((0..100_000).all(|n| is_prime(n) == primes.contains(&n)));
87        // Carmichael numbers and strong pseudoprimes to several small bases.
88        // 3825123056546413051 is a strong pseudoprime to every prime base up to 23.
89        for n in [561u64, 1105, 1729, 2047, 3_215_031_751, 3_825_123_056_546_413_051] {
90            assert!(!is_prime(n), "{n}");
91        }
92        assert!([2, 3, 5, 7, 11, 13, 17, 19, 23].iter().all(|&a| is_strong_probable_prime(3_825_123_056_546_413_051, a)));
93        assert!(is_strong_probable_prime(2047, 2) && !is_prime(2047)); // 2047 = 23 · 89 fools base 2
94        assert!(is_prime(18_446_744_073_709_551_557) && !is_prime(u64::MAX));
95        assert!(is_prime(1_000_000_000_039) && !is_prime(1_000_000_000_037));
96        assert_eq!(next_prime(1_000_000_000_000), Some(1_000_000_000_039));
97        assert_eq!(next_prime(u64::MAX - 1), None);
98        assert_eq!(pow_mod(3, 200, 1_000_000_007), pow_mod(9, 100, 1_000_000_007));
99        assert_eq!(pow_mod(2, 1_000_000_006, 1_000_000_007), 1); // Fermat
100    }
101}