modular arithmetic course - challenge 2 - extended euclidean algorithm

This commit is contained in:
boyreau 2026-11-14 14:31:38 +01:00
commit 4b5f6c47ff
2 changed files with 23 additions and 0 deletions

View file

@ -10,6 +10,7 @@ from intro import (
) )
from modular_arithmetic import ( from modular_arithmetic import (
gcd, gcd,
extended_gcd,
) )
from public_key_cryptography import ( from public_key_cryptography import (
modular_exponentiation, modular_exponentiation,
@ -55,4 +56,5 @@ if __name__ == "__main__":
# Modular arithmetic course challenge # Modular arithmetic course challenge
print(gcd(66528, 52920)) print(gcd(66528, 52920))
print(extended_gcd(26513, 32321))
# fmt: on # fmt: on

View file

@ -5,3 +5,24 @@ def gcd(a: int, b: int) -> int:
a = b a = b
b = r b = r
return a 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]