Extended Euclidean Algorithm
Objective
The Extended Euclidean Algorithm not only computes , but also finds integers and that satisfy:
The pair is also known as the Bézout coefficients.
The Extended Euclidean Algorithm is used to compute the modular inverse of an integer, which is essential in many cryptographic algorithms like RSA, ECC, and digital signatures.
Code (Recursive Version)
def extended_gcd(a, b):
if b == 0:
return (a, 1, 0)
else:
d, x1, y1 = extended_gcd(b, a % b)
x = y1
y = x1 - (a // b) * y1
return (d, x, y)
Proof
Base Case:
If , then:
which satisfies the identity:
Inductive Hypothesis: Assume the recursive call returns such that:
Then:
Now define:
So:
which proves that the identity holds at each step.
Code (Non-Recursive Version)
def extended_gcd(a, b):
# Initialize: (r, s, t) ← (a, 1, 0), (r', s', t') ← (b, 0, 1)
r_prev, r = a, b
s_prev, s = 1, 0
t_prev, t = 0, 1
while r != 0:
q = r_prev // r # quotient
# Update (r, s, t)
r_prev, r = r, r_prev - q * r
s_prev, s = s, s_prev - q * s
t_prev, t = t, t_prev - q * t
# At termination: r_prev = gcd(a, b), s_prev = x, t_prev = y
return r_prev, s_prev, t_prev
Last updated