ctb_formats_math/
primality.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Primality testing and factor verification using Malachite.
21//!
22//! Provides deterministic and probabilistic primality testing for native
23//! unsigned integers and arbitrary-precision `Natural` numbers.
24
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace module prelude"
29)]
30use crate::utilities::*;
31
32use malachite::Natural;
33use malachite::base::num::arithmetic::traits::{
34    CheckedSub, DivExactAssign, DivisibleBy, ModPow, Parity,
35};
36use malachite::base::num::basic::traits::{One, Zero};
37use malachite::base::num::factorization::traits::IsPrime as MalachiteIsPrime;
38
39/// First 25 small prime numbers used for rapid trial division pre-filtering.
40pub const SMALL_PRIMES: &[u32] = &[
41    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
42    73, 79, 83, 89, 97,
43];
44
45/// Deterministic prime testing bases for Miller-Rabin testing up to $2^{64}$.
46pub const MILLER_RABIN_BASES: &[u32] =
47    &[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
48
49/// Checks if a 64-bit integer is prime using Malachite's BPSW algorithm.
50#[must_use]
51pub fn is_prime_u64(n: u64) -> bool {
52    n.is_prime()
53}
54
55/// Checks if an arbitrary-precision `Natural` number is prime using trial
56/// division followed by Miller-Rabin probabilistic primality testing.
57#[must_use]
58pub fn is_prime_natural(n: &Natural) -> bool {
59    let two = Natural::from(2_u32);
60    if *n < two {
61        return false;
62    }
63    if *n == two {
64        return true;
65    }
66    if n.even() {
67        return false;
68    }
69
70    // Trial division against small primes
71    for prime in SMALL_PRIMES {
72        let p_nat = Natural::from(*prime);
73        if *n == p_nat {
74            return true;
75        }
76        if n.divisible_by(&p_nat) {
77            return false;
78        }
79    }
80
81    // If n fits in u64, use fast deterministic check
82    if let Ok(val) = u64::try_from(n) {
83        return val.is_prime();
84    }
85
86    // Write n - 1 = 2^r * d with d odd
87    let Some(n_minus_1) = n.checked_sub(&Natural::ONE) else {
88        return false;
89    };
90    let mut d = n_minus_1.clone();
91    let mut r: u64 = 0;
92    while d.even() {
93        d.div_exact_assign(&two);
94        r = r.saturating_add(1);
95    }
96
97    // Miller-Rabin rounds using fixed prime bases
98    for base in MILLER_RABIN_BASES {
99        let a = Natural::from(*base);
100        if a >= *n {
101            break;
102        }
103        let mut x = (&a).mod_pow(&d, n);
104        if x == Natural::ONE || x == n_minus_1 {
105            continue;
106        }
107
108        let mut composite = true;
109        let mut count: u64 = 1;
110        while count < r {
111            x = (&x).mod_pow(&two, n);
112            if x == n_minus_1 {
113                composite = false;
114                break;
115            }
116            count = count.saturating_add(1);
117        }
118
119        if composite {
120            return false;
121        }
122    }
123
124    true
125}
126
127#[cfg(test)]
128#[allow(
129    clippy::panic,
130    clippy::expect_used,
131    clippy::unwrap_used,
132    clippy::unwrap_in_result,
133    clippy::panic_in_result_fn,
134    clippy::indexing_slicing,
135    clippy::arithmetic_side_effects,
136    reason = "Standard repository test boilerplate"
137)]
138mod tests {
139    use super::*;
140
141    #[crate::ctb_test]
142    fn test_is_prime_natural_small_and_large() {
143        assert!(!is_prime_natural(&Natural::from(0_u32)));
144        assert!(!is_prime_natural(&Natural::from(1_u32)));
145        assert!(is_prime_natural(&Natural::from(2_u32)));
146        assert!(is_prime_natural(&Natural::from(3_u32)));
147        assert!(!is_prime_natural(&Natural::from(4_u32)));
148        assert!(is_prime_natural(&Natural::from(17_u32)));
149        assert!(!is_prime_natural(&Natural::from(561_u32))); // Carmichael number
150
151        // 32-bit FNV prime: 2^24 + 2^8 + 0x93 = 16777619
152        assert!(is_prime_natural(&Natural::from(16_777_619_u32)));
153
154        // 64-bit FNV prime: 2^40 + 2^8 + 0xb3 = 1099511628211
155        assert!(is_prime_natural(&Natural::from(1_099_511_628_211_u64)));
156
157        // 128-bit FNV prime: 2^88 + 2^8 + 0x3b
158        let p128 = (Natural::ONE << 88_u32)
159            + (Natural::ONE << 8_u32)
160            + Natural::from(0x3b_u32);
161        assert!(is_prime_natural(&p128));
162    }
163}