Lesson 5 of 15
Extended Euclidean Algorithm
Extended Euclidean Algorithm
The Extended Euclidean Algorithm does more than just find . It also finds integers and such that:
This is known as Bezout's identity, and the pair is called a Bezout coefficient pair. These coefficients are essential for computing modular inverses and solving linear Diophantine equations.
The Recursion
The algorithm extends the standard Euclidean recursion. If , we track coefficients backward:
Then the coefficients for the original are:
def extended_gcd(a, b):
if b == 0:
return a, 1, 0 # gcd=a, x=1, y=0 since a*1 + 0*0 = a
g, x, y = extended_gcd(b, a % b)
return g, y, x - (a // b) * y
g, x, y = extended_gcd(35, 15)
print(g, x, y) # 5 1 -2
# Verify: 35*1 + 15*(-2) = 35 - 30 = 5 ✓
Applications
- Modular inverse: if then from gives
- Chinese Remainder Theorem: solve systems of congruences
- Linear Diophantine equations: has integer solutions iff
Your Task
Implement extended_gcd(a, b) that returns a tuple (g, x, y) where and .
Python runtime loading...
Loading...
Click "Run" to execute your code.