Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) ** extended_gcd function is used when d = gcd(a,b) is required in output
(a: int, b: int)
| 80 | |
| 81 | |
| 82 | def extended_gcd(a: int, b: int) -> tuple[int, int, int]: |
| 83 | """ |
| 84 | Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x |
| 85 | and y, then d = gcd(a,b) |
| 86 | >>> extended_gcd(10, 6) |
| 87 | (2, -1, 2) |
| 88 | |
| 89 | >>> extended_gcd(7, 5) |
| 90 | (1, -2, 3) |
| 91 | |
| 92 | ** extended_gcd function is used when d = gcd(a,b) is required in output |
| 93 | |
| 94 | """ |
| 95 | assert a >= 0 |
| 96 | assert b >= 0 |
| 97 | |
| 98 | if b == 0: |
| 99 | d, x, y = a, 1, 0 |
| 100 | else: |
| 101 | (d, p, q) = extended_gcd(b, a % b) |
| 102 | x = q |
| 103 | y = p - q * (a // b) |
| 104 | |
| 105 | assert a % d == 0 |
| 106 | assert b % d == 0 |
| 107 | assert d == a * x + b * y |
| 108 | |
| 109 | return (d, x, y) |
| 110 | |
| 111 | |
| 112 | def extended_euclid(a: int, b: int) -> tuple[int, int]: |