def extended_euclid(a: int, b: int) -> Tuple[int, int, int]:
"""Extended Euclidean algorithm that computes the Bézout coefficients as well as :math:`gcd(a, b)`
Returns ``x, y, d`` where *x* and *y* are a solution to :math:`ax + by = d` and :math:`d = gcd(a, b)`.
*x* and *y* are a minimal pair of Bézout's coefficients.
See `Extended Euclidean algorithm <https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm>`_ or
`Bézout's identity <https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity>`_ for more information.
Example:
Compute the Bézout coefficients and GCD of 42 and 12:
>>> a, b = 42, 12
>>> x, y, d = extended_euclid(a, b)
>>> x, y, d
(1, -3, 6)
Verify the results:
>>> import math
>>> d == math.gcd(a, b)
True
>>> a * x + b * y == d
True
Args:
a:
The first integer.
b:
The second integer.
Returns:
A tuple with the Bézout coefficients and the greatest common divider of the arguments.
"""
if b == 0:
return (1, 0, a)
x0, y0, d = extended_euclid(b, a % b)
x, y = y0, x0 - (a // b) * y0
return (x, y, d)
评论列表
文章目录