Skip to main content

lib_jsl_number_theory/
greatest_common_divisor.rs

1//! Greatest common divisors and Bézout coefficients by Euclid's algorithm.
2//!
3//! See the book entry [Divisibility and modular arithmetic](https://jwkunz.github.io/lib_jsl/book/number-theory/modular-arithmetic.html).
4
5/// Computes the greatest common divisor (GCD) of two integers using the
6/// classical Euclidean algorithm.
7///
8/// # Overview
9/// The greatest common divisor of two integers is the largest positive integer
10/// that divides both numbers without leaving a remainder. This implementation
11/// uses the Euclidean algorithm, based on
12///
13/// ```text
14/// gcd(a, b) = gcd(b, a mod b)
15/// ```
16///
17/// repeated until the second operand becomes zero; the first operand is then
18/// the GCD up to sign, and its absolute value is returned.
19///
20/// # Properties
21/// - **Time Complexity:** O(log(min(|a|, |b|)))
22/// - **Space Complexity:** O(1)
23///
24/// # Edge Cases
25/// - The result is never negative: `gcd(4, -6) = 2`.
26/// - If one of the inputs is zero, the function returns the absolute value of the other.
27/// - If both inputs are zero, the function returns zero (a common convention).
28/// - `i128::MIN` with zero (or with itself) has no representable GCD and overflows.
29pub fn gcd(mut a: i128, mut b: i128) -> i128 {
30    while b != 0 {
31        let remainder = a % b;
32        a = b;
33        b = remainder;
34    }
35    a.abs()
36}
37
38/// Computes the greatest common divisor (GCD) of two integers and finds
39/// integer coefficients `x` and `y` such that:
40///
41/// ```text
42/// a·x + b·y = gcd(a, b)
43/// ```
44///
45/// # Overview
46/// This function implements the **Extended Euclidean Algorithm**, which extends
47/// the classical Euclidean algorithm by additionally computing the Bézout
48/// coefficients, as used for modular inverses and the Chinese remainder theorem.
49/// The algorithm keeps the invariant `a·s + b·t = r` for each remainder `r`
50/// while running the Euclidean recurrence `gcd(a, b) = gcd(b, a mod b)`.
51///
52/// # Properties
53/// - **Time Complexity:** O(log(min(|a|, |b|)))
54/// - **Space Complexity:** O(1)
55///
56/// # Edge Cases
57/// - The returned `g` is never negative (the coefficients' signs are adjusted to match).
58/// - If `b == 0`, the function returns `(|a|, ±1, 0)`.
59/// - If both inputs are zero, the function returns `(0, 0, 0)`.
60///
61/// # Returns
62/// A tuple `(g, x, y)` where:
63/// - `g` is the greatest common divisor of `a` and `b`
64/// - `x` and `y` are integers satisfying `a·x + b·y = g`
65pub fn extended_gcd(a: i128, b: i128) -> (i128, i128, i128) {
66    // Handle the degenerate case explicitly
67    if a == 0 && b == 0 {
68        return (0, 0, 0);
69    }
70
71    // Convert to signed integers for coefficient arithmetic
72    let mut old_r: i128 = a;
73    let mut r: i128 = b;
74
75    let mut old_s: i128 = 1;
76    let mut s: i128 = 0;
77
78    let mut old_t: i128 = 0;
79    let mut t: i128 = 1;
80
81    // ANCHOR: extended_euclid
82    while r != 0 {
83        let quotient = old_r / r;
84
85        let temp_r = old_r - quotient * r;
86        old_r = r;
87        r = temp_r;
88
89        let temp_s = old_s - quotient * s;
90        old_s = s;
91        s = temp_s;
92
93        let temp_t = old_t - quotient * t;
94        old_t = t;
95        t = temp_t;
96    }
97    // ANCHOR_END: extended_euclid
98
99    // At this point old_r is the GCD up to sign, and old_s and old_t are the Bézout
100    // coefficients; make the GCD non-negative.
101    if old_r < 0 {
102        (-old_r, -old_s, -old_t)
103    } else {
104        (old_r, old_s, old_t)
105    }
106}
107
108#[cfg(test)]
109mod test{
110    use super::*;
111
112    #[test]
113    fn the_gcd_is_never_negative() {
114        assert_eq!(gcd(4, -6), 2);
115        assert_eq!(gcd(-4, -6), 2);
116        assert_eq!(gcd(-5, 0), 5);
117        for (a, b) in [(4i128, -6i128), (-4, 6), (-4, -6), (-35, 0), (0, -9), (240, -46)] {
118            let (g, x, y) = extended_gcd(a, b);
119            assert!(g >= 0 && a * x + b * y == g && g == gcd(a, b), "({a}, {b}) -> ({g}, {x}, {y})");
120        }
121    }
122
123    #[test]
124    fn test_gcd(){
125        let a = 12;
126        let b = 21;
127        let g = gcd(a, b);
128        assert_eq!(g,3);
129        let (g,x,y) = extended_gcd(a,b);
130        assert_eq!(g,3);
131        assert_eq!(x,2);
132        assert_eq!(y,-1);
133    }
134}