diff --git a/challenge.py b/challenge.py index b45ce1a..6d1cc80 100644 --- a/challenge.py +++ b/challenge.py @@ -10,6 +10,7 @@ from intro import ( ) from modular_arithmetic import ( gcd, + extended_gcd, ) from public_key_cryptography import ( modular_exponentiation, @@ -55,4 +56,5 @@ if __name__ == "__main__": # Modular arithmetic course challenge print(gcd(66528, 52920)) + print(extended_gcd(26513, 32321)) # fmt: on diff --git a/modular_arithmetic.py b/modular_arithmetic.py index 448227f..5cf5f2f 100644 --- a/modular_arithmetic.py +++ b/modular_arithmetic.py @@ -5,3 +5,24 @@ def gcd(a: int, b: int) -> int: a = b b = r return a + + +# Challenge 2 - extended Euclidean algorithm +def extended_gcd(a: int, b: int) -> (int, int, int): + """ + Args: + a: an integer + b: an integer + Returns: + (gcd, u, v) so that u*a + v*b = gcd + """ + u = [1, 0] + v = [0, 1] + while b != 0: + r = a % b + q = a // b + u.append(u[-2] - u[-1] * q) + v.append(v[-2] - v[-1] * q) + a = b + b = r + return a, u[-2], v[-2]