pub fn extended_gcd(a: i128, b: i128) -> (i128, i128, i128)Expand description
Computes the greatest common divisor (GCD) of two integers and finds
integer coefficients x and y such that:
a·x + b·y = gcd(a, b)§Overview
This function implements the Extended Euclidean Algorithm, which extends
the classical Euclidean algorithm by additionally computing the Bézout
coefficients, as used for modular inverses and the Chinese remainder theorem.
The algorithm keeps the invariant a·s + b·t = r for each remainder r
while running the Euclidean recurrence gcd(a, b) = gcd(b, a mod b).
§Properties
- Time Complexity: O(log(min(|a|, |b|)))
- Space Complexity: O(1)
§Edge Cases
- The returned
gis never negative (the coefficients’ signs are adjusted to match). - If
b == 0, the function returns(|a|, ±1, 0). - If both inputs are zero, the function returns
(0, 0, 0).
§Returns
A tuple (g, x, y) where:
gis the greatest common divisor ofaandbxandyare integers satisfyinga·x + b·y = g