lib_jsl_number_theory/
primality.rs1pub fn mul_mod(a: u64, b: u64, m: u64) -> u64 {
7 ((a as u128 * b as u128) % m as u128) as u64
8}
9
10pub 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
24pub 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 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 }
52
53pub 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
73pub 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 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)); 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); }
101}