Extended Euclidean Algorithm. Finds 2 numbers a and b such that it satisfies the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) >>> extended_euclidean_algorithm(1, 24) (1, 0) >>> extended_euclidean_algorithm(8, 14) (2, -1) >>> extended_euclidean_algorithm
(a: int, b: int)
| 18 | |
| 19 | |
| 20 | def extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]: |
| 21 | """ |
| 22 | Extended Euclidean Algorithm. |
| 23 | |
| 24 | Finds 2 numbers a and b such that it satisfies |
| 25 | the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) |
| 26 | |
| 27 | >>> extended_euclidean_algorithm(1, 24) |
| 28 | (1, 0) |
| 29 | |
| 30 | >>> extended_euclidean_algorithm(8, 14) |
| 31 | (2, -1) |
| 32 | |
| 33 | >>> extended_euclidean_algorithm(240, 46) |
| 34 | (-9, 47) |
| 35 | |
| 36 | >>> extended_euclidean_algorithm(1, -4) |
| 37 | (1, 0) |
| 38 | |
| 39 | >>> extended_euclidean_algorithm(-2, -4) |
| 40 | (-1, 0) |
| 41 | |
| 42 | >>> extended_euclidean_algorithm(0, -4) |
| 43 | (0, -1) |
| 44 | |
| 45 | >>> extended_euclidean_algorithm(2, 0) |
| 46 | (1, 0) |
| 47 | |
| 48 | """ |
| 49 | # base cases |
| 50 | if abs(a) == 1: |
| 51 | return a, 0 |
| 52 | elif abs(b) == 1: |
| 53 | return 0, b |
| 54 | |
| 55 | old_remainder, remainder = a, b |
| 56 | old_coeff_a, coeff_a = 1, 0 |
| 57 | old_coeff_b, coeff_b = 0, 1 |
| 58 | |
| 59 | while remainder != 0: |
| 60 | quotient = old_remainder // remainder |
| 61 | old_remainder, remainder = remainder, old_remainder - quotient * remainder |
| 62 | old_coeff_a, coeff_a = coeff_a, old_coeff_a - quotient * coeff_a |
| 63 | old_coeff_b, coeff_b = coeff_b, old_coeff_b - quotient * coeff_b |
| 64 | |
| 65 | # sign correction for negative numbers |
| 66 | if a < 0: |
| 67 | old_coeff_a = -old_coeff_a |
| 68 | if b < 0: |
| 69 | old_coeff_b = -old_coeff_b |
| 70 | |
| 71 | return old_coeff_a, old_coeff_b |
| 72 | |
| 73 | |
| 74 | def main(): |