Skip to main content

lib_jsl_number_theory/
multiplicative_inverse_modulo.rs

1//! Modular multiplicative inverses.
2//!
3//! See the book entry [Divisibility and modular arithmetic](https://jwkunz.github.io/lib_jsl/book/number-theory/modular-arithmetic.html).
4
5use crate::greatest_common_divisor::extended_gcd;
6use lib_jsl_core::ErrorsJSL;
7
8/// Computes the multiplicative inverse of `a` modulo `m` using the
9/// Extended Euclidean Algorithm.
10///
11/// # Mathematical Background
12///
13/// The multiplicative inverse of an integer `a` modulo `m` is an integer `a⁻¹`
14/// such that:
15///
16/// ```text
17/// (a * a⁻¹) ≡ 1 (mod m)
18/// ```
19///
20/// Such an inverse exists if and only if `a` and `m` are coprime, i.e.,
21///
22/// ```text
23/// gcd(a, m) = 1
24/// ```
25///
26/// The Extended Euclidean Algorithm finds integers `x` and `y` satisfying:
27///
28/// ```text
29/// a·x + m·y = gcd(a, m)
30/// ```
31///
32/// When `gcd(a, m) = 1`, the coefficient `x` is the modular inverse of `a`
33/// modulo `m`.
34///
35/// # Parameters
36///
37/// * `a` – The integer whose modular inverse is to be computed.
38/// * `m` – The modulus. Must be nonzero.
39///
40/// # Returns
41///
42/// * `Ok(inv)` – The modular inverse of `a` modulo `m`, normalized to the
43///   range `[0, |m| - 1]`.
44/// * `Err(ErrorsJSL)` – If `m` is zero or the modular inverse does not exist.
45///
46/// # Errors
47///
48/// Returns an error if `gcd(a, m) ≠ 1`, meaning the inverse does not exist.
49///
50///
51/// # Complexity
52///
53/// Runs in **O(log m)** time and **O(1)** space.
54pub fn multiplicative_inverse_modulo(a: i128, m: i128) -> Result<i128, ErrorsJSL> {
55    if m == 0 {
56        return Err(ErrorsJSL::InvalidInputRange("m must be non-zero"));
57    }
58
59    let (g, x, _) = extended_gcd(a, m);
60
61    if g != 1 {
62        return Err(ErrorsJSL::RuntimeError("modular inverse does not exist (inputs are not coprime)"));
63    }
64
65    // Normalize the result into the range [0, |m| - 1]
66    Ok(x.rem_euclid(m.abs()))
67}
68
69#[cfg(test)]
70mod test{
71    use super::*;
72
73    #[test]
74    fn test_multiplicative_inverse_modulo(){
75        let a = 12;
76        let m = 25;
77        let b = multiplicative_inverse_modulo(a,m).unwrap();
78        assert_eq!((a*b)%m,1)
79    }
80
81    #[test]
82    fn negative_moduli_give_inverses_in_range(){
83        let inv = multiplicative_inverse_modulo(3, -7).unwrap();
84        assert!((0..7).contains(&inv) && (3 * inv).rem_euclid(7) == 1);
85        assert!(multiplicative_inverse_modulo(4, 0).is_err() && multiplicative_inverse_modulo(4, 6).is_err());
86    }
87}