Skip to main content

lib_jsl_number_theory/
base_exponent_in_modulus.rs

1//! Modular exponentiation by square-and-multiply.
2//!
3//! See the book entry [Divisibility and modular arithmetic](https://jwkunz.github.io/lib_jsl/book/number-theory/modular-arithmetic.html).
4
5use lib_jsl_core::ErrorsJSL;
6
7/// Computes modular exponentiation using exponentiation by squaring.
8///
9/// This function calculates:
10///
11/// ```text
12/// (base ^ exponent) mod modulus
13/// ```
14///
15/// using 128-bit signed integers (`i128`). It is efficient for large exponents,
16/// running in `O(log exponent)` time.
17///
18/// # Parameters
19///
20/// * `base` - The base value.
21/// * `exponent` - The exponent. Must be non-negative.
22/// * `modulus` - The modulus. Must be greater than zero.
23///
24/// # Returns
25///
26/// The result of `(base ^ exponent) % modulus`, normalized to the range
27/// `[0, modulus - 1]`.
28///
29/// # Errors
30///
31/// This function will error if:
32///
33/// * `modulus <= 0`
34/// * `exponent < 0`
35///
36/// # Notes
37///
38/// * The base is normalized modulo `modulus` before computation.
39/// * Products are formed in 128-bit unsigned arithmetic when they fit and by
40///   double-and-add otherwise, so every positive `i128` modulus is handled
41///   without overflow.
42pub fn base_exponent_in_modulus(base: i128, exponent: i128, modulus: i128) -> Result<i128, ErrorsJSL> {
43    if modulus <= 0 {
44        return Err(ErrorsJSL::InvalidInputRange("modulus must be greater than zero"));
45    }
46    if exponent < 0 {
47        return Err(ErrorsJSL::InvalidInputRange("exponent must be nonnegative"));
48    }
49
50    // Work with residues in [0, modulus), as u128.
51    let m = modulus as u128;
52    let mut base = base.rem_euclid(modulus) as u128;
53    let mut exp = exponent;
54    let mut result: u128 = 1 % m;
55
56    // ANCHOR: square_and_multiply
57    while exp > 0 {
58        // If the current exponent bit is set, multiply result by base
59        if exp & 1 == 1 {
60            result = mul_mod_u128(result, base, m);
61        }
62
63        // Square the base and reduce modulo
64        base = mul_mod_u128(base, base, m);
65
66        // Shift exponent right by one bit
67        exp >>= 1;
68    }
69    // ANCHOR_END: square_and_multiply
70
71    Ok(result as i128)
72}
73
74/// `a ยท b mod m` for `a, b < m < 2^127`, without overflow.
75fn mul_mod_u128(a: u128, b: u128, m: u128) -> u128 {
76    if let Some(product) = a.checked_mul(b) {
77        return product % m;
78    }
79    // Double-and-add: every intermediate is below 2m < 2^128.
80    let (mut result, mut a, mut b) = (0u128, a, b);
81    while b > 0 {
82        if b & 1 == 1 {
83            result = (result + a) % m;
84        }
85        a = (a + a) % m;
86        b >>= 1;
87    }
88    result
89}
90
91#[cfg(test)]
92mod test{
93    use super::*;
94
95    #[test]
96    fn invalid_arguments_are_errors_and_large_moduli_do_not_overflow() {
97        // A zero modulus used to reach `% 0` and panic.
98        assert!(base_exponent_in_modulus(3, 4, 0).is_err());
99        assert!(base_exponent_in_modulus(3, 4, -7).is_err());
100        assert!(base_exponent_in_modulus(3, -1, 7).is_err());
101        assert_eq!(base_exponent_in_modulus(-2, 3, 7).unwrap(), 6); // (โˆ’8) mod 7
102        // Fermat's little theorem for the Mersenne prime 2^89 โˆ’ 1 and for 2^127 โˆ’ 1, whose
103        // squares overflow 128 bits.
104        for p in [(1i128 << 89) - 1, i128::MAX] {
105            assert_eq!(base_exponent_in_modulus(3, p - 1, p).unwrap(), 1);
106            assert_eq!(base_exponent_in_modulus(12345, p, p).unwrap(), 12345);
107        }
108    }
109
110    #[test]
111    fn test_base_exponent_in_modulus(){
112        let result = base_exponent_in_modulus(2, 10, 1_000).unwrap();
113        assert_eq!(result, 24); // 2^10 = 1024, 1024 % 1000 = 24
114        let result = base_exponent_in_modulus(-2, 3, 5).unwrap();
115        assert_eq!(result, 2); // (-2)^3 = -8, -8 mod 5 = 2
116    }
117}