Home DSA Extended Euclidean Algorithm: Bezout's Identity & Modular Inverses
Intermediate 3 min · July 14, 2026

Extended Euclidean Algorithm: Bezout's Identity & Modular Inverses

Master the Extended Euclidean Algorithm: find modular inverses, solve linear Diophantine equations, and understand Bezout's Identity with Python code and real-world debugging tips..

N
Naren Founder & Principal Engineer

20+ years shipping performance-critical code where algorithms decide the bill. Drawn from code that ran under real load.

Follow
Production
production tested
July 15, 2026
last updated
2,398
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic understanding of the Euclidean algorithm for GCD
  • Familiarity with modular arithmetic
  • Basic Python programming
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • The Extended Euclidean Algorithm finds integers x and y such that ax + by = gcd(a, b).
  • It is used to compute modular inverses, which are essential in cryptography (e.g., RSA).
  • The algorithm extends the standard Euclidean algorithm by keeping track of coefficients.
  • It can solve linear Diophantine equations of the form ax + by = c.
  • Time complexity is O(log min(a, b)).
✦ Definition~90s read
What is Extended Euclidean Algorithm?

The Extended Euclidean Algorithm is an extension of the Euclidean algorithm that finds integers x and y such that ax + by = gcd(a, b), enabling you to compute modular inverses and solve linear Diophantine equations.

Imagine you have two numbers, like 30 and 12.
Plain-English First

Imagine you have two numbers, like 30 and 12. The Euclidean algorithm finds the biggest number that divides both (the GCD). The Extended version not only finds that number but also tells you how to combine the original numbers to get it. It's like having two ingredients and finding the exact recipe to make a specific dish.

Have you ever needed to find a number that, when multiplied by another, gives a remainder of 1? That's a modular inverse, and it's crucial in cryptography, hash functions, and more. The Extended Euclidean Algorithm is the tool that makes this possible. It's a classic number theory algorithm that not only computes the greatest common divisor (GCD) of two integers but also finds the coefficients of Bezout's identity: integers x and y such that ax + by = gcd(a, b). This might sound abstract, but it has direct applications: from solving linear Diophantine equations to computing modular inverses for RSA encryption. In this tutorial, you'll learn how the algorithm works, see it in action with Python code, and understand how to use it in production systems. We'll also cover common pitfalls and debugging strategies. By the end, you'll be able to implement the Extended Euclidean Algorithm confidently and apply it to real-world problems.

Understanding the Euclidean Algorithm

The Euclidean algorithm is a method for finding the greatest common divisor (GCD) of two integers. It is based on the principle that gcd(a, b) = gcd(b, a mod b). The algorithm repeatedly replaces (a, b) with (b, a % b) until b becomes 0, at which point a is the GCD. For example, to find gcd(30, 12): 30 % 12 = 6, so next pair is (12, 6) 12 % 6 = 0, so next pair is (6, 0) => GCD = 6. This is simple and efficient with O(log min(a, b)) time complexity.

euclidean.pyPYTHON
1
2
3
4
5
6
7
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

print(gcd(30, 12))  # Output: 6
print(gcd(17, 5))   # Output: 1
Output
6
1
🔥Why Euclidean Algorithm?
📊 Production Insight
In production, ensure that inputs are non-negative integers. Negative numbers can be handled by taking absolute values, but be consistent.
🎯 Key Takeaway
The Euclidean algorithm efficiently computes GCD using repeated modulo operations.
extended-euclidean-algorithm THECODEFORGE.IO Extended Euclidean Algorithm Flow Step-by-step process to compute gcd and coefficients Initialize Set r0 = a, r1 = b, s0 = 1, s1 = 0, t0 = 0, t1 = 1 Divide Compute quotient q = r_{i-1} // r_i Update Remainders r_{i+1} = r_{i-1} - q * r_i Update Coefficients s_{i+1} = s_{i-1} - q * s_i, t_{i+1} = t_{i-1} - q * t_i Check Termination If r_{i+1} == 0, stop; else repeat Output gcd = r_i, Bezout coefficients s_i, t_i ⚠ Forgetting to update both s and t coefficients Always update s and t in parallel with remainders THECODEFORGE.IO
thecodeforge.io
Extended Euclidean Algorithm

Bezout's Identity: The Core Concept

Bezout's Identity states that for any integers a and b, there exist integers x and y such that ax + by = gcd(a, b). These coefficients are not unique; the Extended Euclidean Algorithm finds one such pair. For example, for a=30 and b=12, gcd=6, and we have 301 + 12(-2) = 6. This identity is fundamental in solving linear Diophantine equations and computing modular inverses. The coefficients can be found by backtracking through the Euclidean algorithm steps.

bezout_example.pyPYTHON
1
2
3
4
5
# Manual backtracking for gcd(30,12):
# Step1: 30 = 2*12 + 6  => 6 = 30 - 2*12
# Step2: 12 = 2*6 + 0   => stop
# So 6 = 30*1 + 12*(-2) => x=1, y=-2
print(f"30*1 + 12*(-2) = {30*1 + 12*(-2)}")  # Output: 6
Output
30*1 + 12*(-2) = 6
💡Bezout's Identity Existence
🎯 Key Takeaway
Bezout's Identity guarantees that we can express the GCD as a linear combination of the original numbers.

Implementing the Extended Euclidean Algorithm

The Extended Euclidean Algorithm computes the GCD along with the coefficients x and y. It can be implemented recursively or iteratively. The recursive version follows the recurrence: if b == 0, return (a, 1, 0). Otherwise, recursively compute (g, x1, y1) for (b, a % b), then return (g, y1, x1 - (a // b) * y1). The iterative version uses a loop to update coefficients. Both have O(log min(a, b)) time complexity. Here's a Python implementation:

extended_gcd.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
def extended_gcd(a, b):
    if b == 0:
        return (a, 1, 0)
    else:
        g, x1, y1 = extended_gcd(b, a % b)
        x = y1
        y = x1 - (a // b) * y1
        return (g, x, y)

print(extended_gcd(30, 12))  # Output: (6, 1, -2)
print(extended_gcd(17, 5))   # Output: (1, -2, 7)
Output
(6, 1, -2)
(1, -2, 7)
⚠ Recursion Depth
📊 Production Insight
Always test with edge cases: a=0, b=0, negative numbers. For a=0, gcd(0,b)=|b|, and coefficients are (0, sign(b)).
🎯 Key Takeaway
The Extended Euclidean Algorithm returns (gcd, x, y) such that ax + by = gcd.
extended-euclidean-algorithm THECODEFORGE.IO Extended Euclidean Algorithm Architecture Layered components from input to modular inverse Input Layer Integers a and b | Modulus m Core Algorithm Layer Euclidean Division | Remainder Sequence | Coefficient Update Bezout Identity Layer Compute s, t coefficients | Verify gcd = s*a + t*b Modular Inverse Layer Check gcd(a, m) = 1 | Compute a^{-1} mod m = s mod m Output Layer gcd | Bezout coefficients | Modular inverse (if exists) THECODEFORGE.IO
thecodeforge.io
Extended Euclidean Algorithm

Computing Modular Inverses

A modular inverse of a modulo m is an integer x such that ax ≡ 1 (mod m). This exists only if gcd(a, m) = 1. Using the Extended Euclidean Algorithm, we find x and y such that ax + my = 1. Then x mod m is the modular inverse. For example, to find the inverse of 17 modulo 43: extended_gcd(17, 43) returns (1, -5, 2) because 17(-5) + 43*2 = 1. So the inverse is -5 mod 43 = 38. In Python, we can compute it as:

mod_inverse.pyPYTHON
1
2
3
4
5
6
7
8
9
def mod_inverse(a, m):
    g, x, y = extended_gcd(a, m)
    if g != 1:
        raise ValueError('Inverse does not exist')
    else:
        return x % m

print(mod_inverse(17, 43))  # Output: 38
print(mod_inverse(30, 12))  # Raises ValueError
Output
38
ValueError: Inverse does not exist
💡Normalization
📊 Production Insight
In cryptographic libraries, modular inverse is often implemented with constant-time algorithms to prevent side-channel attacks. For general use, the Extended Euclidean Algorithm is sufficient.
🎯 Key Takeaway
Modular inverses are computed using the Extended Euclidean Algorithm when gcd(a, m) = 1.

Solving Linear Diophantine Equations

A linear Diophantine equation is of the form ax + by = c. It has integer solutions if and only if gcd(a, b) divides c. The Extended Euclidean Algorithm provides a particular solution (x0, y0) for ax + by = g. Then all solutions are given by x = x0(c/g) + (b/g)t, y = y0(c/g) - (a/g)t for integer t. For example, solve 30x + 12y = 18. Since gcd=6 divides 18, solutions exist. From extended_gcd(30,12) we have (6,1,-2). Multiply by 3: x0=3, y0=-6. General solution: x=3 + 2t, y=-6 -5t.

diophantine.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def solve_diophantine(a, b, c):
    g, x0, y0 = extended_gcd(a, b)
    if c % g != 0:
        return None  # No solution
    x0 *= c // g
    y0 *= c // g
    return (x0, y0, b // g, a // g)  # returns particular solution and step sizes

sol = solve_diophantine(30, 12, 18)
if sol:
    x0, y0, step_x, step_y = sol
    print(f"Particular: x={x0}, y={y0}")
    print(f"General: x = {x0} + {step_x}*t, y = {y0} - {step_y}*t")
else:
    print("No solution")
Output
Particular: x=3, y=-6
General: x = 3 + 2*t, y = -6 - 5*t
🔥Applications
🎯 Key Takeaway
The Extended Euclidean Algorithm provides a particular solution to linear Diophantine equations, from which all solutions can be derived.
Recursive vs Iterative Extended Euclidean Trade-offs in implementation approaches Recursive Iterative Code Complexity Simple, elegant recursion More verbose loop logic Memory Usage O(log n) stack frames O(1) extra space Performance Overhead from function calls Faster in practice, no recursion Readability Easy to understand mathematically Clear for production code Risk of Stack Overflow Possible for large inputs No recursion, safe for all sizes THECODEFORGE.IO
thecodeforge.io
Extended Euclidean Algorithm

Iterative Implementation for Production

The recursive implementation is elegant but may cause stack overflow for large inputs. An iterative version is more robust for production. It uses a loop to update coefficients similarly to the recursive version. Here's an iterative implementation:

extended_gcd_iterative.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
def extended_gcd_iterative(a, b):
    old_r, r = a, b
    old_s, s = 1, 0
    old_t, t = 0, 1
    while r != 0:
        quotient = old_r // r
        old_r, r = r, old_r - quotient * r
        old_s, s = s, old_s - quotient * s
        old_t, t = t, old_t - quotient * t
    return (old_r, old_s, old_t)

print(extended_gcd_iterative(30, 12))  # Output: (6, 1, -2)
print(extended_gcd_iterative(17, 5))   # Output: (1, -2, 7)
Output
(6, 1, -2)
(1, -2, 7)
💡Memory Efficiency
📊 Production Insight
In performance-critical code, consider using built-in functions like pow(a, -1, m) in Python 3.8+ for modular inverses, which is implemented in C and is faster.
🎯 Key Takeaway
Use the iterative version in production to avoid recursion depth issues.
● Production incidentPOST-MORTEMseverity: high

The RSA Key Generation Outage

Symptom
RSA key generation failed intermittently with 'Invalid private exponent' errors.
Assumption
The random prime generation was flawed.
Root cause
The modular inverse computation using the Extended Euclidean Algorithm had a bug when the modulus was not prime, leading to incorrect private exponents.
Fix
Replaced the custom modular inverse implementation with a well-tested library function and added input validation.
Key lesson
  • Always use battle-tested libraries for cryptographic operations.
  • Validate that the modulus and the number are coprime before computing modular inverse.
  • Handle edge cases like negative numbers and zero inputs.
  • Write unit tests for the Extended Euclidean Algorithm with known values.
  • Log intermediate values for debugging in production.
Production debug guideSymptom to Action3 entries
Symptom · 01
Modular inverse returns 0 or negative number
Fix
Check that the input number and modulus are coprime (gcd == 1). If not, no inverse exists. Ensure the result is normalized to be positive.
Symptom · 02
Algorithm returns wrong GCD
Fix
Verify that the recursive or iterative implementation correctly updates coefficients. Test with simple pairs like (30, 12) expecting GCD=6 and coefficients (1, -2).
Symptom · 03
Stack overflow for large inputs
Fix
Use an iterative implementation instead of recursive to avoid stack overflow. Python's recursion limit may be hit for large numbers.
★ Quick Debug Cheat SheetFor when the Extended Euclidean Algorithm fails in production.
Modular inverse doesn't exist
Immediate action
Check gcd(a, m) == 1
Commands
import math; print(math.gcd(a, m))
if math.gcd(a, m) != 1: raise ValueError('No inverse')
Fix now
Ensure a and m are coprime.
Negative coefficients+
Immediate action
Normalize to positive modulo m
Commands
x = x % m
print(x) # should be between 0 and m-1
Fix now
Add m to x if negative.
Incorrect GCD+
Immediate action
Test with known values
Commands
print(extended_gcd(30, 12)) # should be (6, 1, -2)
print(extended_gcd(17, 5)) # should be (1, -2, 7)
Fix now
Check coefficient update logic.
AlgorithmInputOutputTime ComplexityUse Case
Euclidean Algorithma, bgcd(a, b)O(log min(a,b))Computing GCD
Extended Euclidean Algorithma, b(gcd, x, y) such that ax+by=gcdO(log min(a,b))Modular inverses, Diophantine equations
Binary GCD Algorithma, bgcd(a, b)O(log min(a,b))Faster on some hardware
⚙ Quick Reference
6 commands from this guide
FileCommand / CodePurpose
euclidean.pydef gcd(a, b):Understanding the Euclidean Algorithm
bezout_example.pyprint(f"30*1 + 12*(-2) = {30*1 + 12*(-2)}") # Output: 6Bezout's Identity
extended_gcd.pydef extended_gcd(a, b):Implementing the Extended Euclidean Algorithm
mod_inverse.pydef mod_inverse(a, m):Computing Modular Inverses
diophantine.pydef solve_diophantine(a, b, c):Solving Linear Diophantine Equations
extended_gcd_iterative.pydef extended_gcd_iterative(a, b):Iterative Implementation for Production

Key takeaways

1
The Extended Euclidean Algorithm computes gcd(a, b) and coefficients x, y such that ax + by = gcd.
2
It is used to compute modular inverses, which are essential in cryptography.
3
The algorithm runs in O(log min(a, b)) time and can be implemented iteratively to avoid recursion limits.
4
Always normalize the modular inverse to be positive and check for existence (gcd == 1).
5
Linear Diophantine equations can be solved using the particular solution from the algorithm.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
Implement the Extended Euclidean Algorithm recursively and explain how i...
Q02SENIOR
Given two numbers a and b, find the modular inverse of a modulo b using ...
Q03SENIOR
Solve the linear Diophantine equation 15x + 25y = 10. If no solution, ex...
Q01 of 03SENIOR

Implement the Extended Euclidean Algorithm recursively and explain how it works.

ANSWER
See the recursive implementation in the article. It returns (gcd, x, y) such that ax + by = gcd. The base case is b=0, returning (a,1,0). Otherwise, it recurses with (b, a%b) and updates coefficients.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
What is the difference between Euclidean and Extended Euclidean Algorithm?
02
When does a modular inverse not exist?
03
Can the Extended Euclidean Algorithm handle negative numbers?
04
What is the time complexity of the Extended Euclidean Algorithm?
05
How do I compute the modular inverse in Python without implementing the algorithm?
N
Naren Founder & Principal Engineer

20+ years shipping performance-critical code where algorithms decide the bill. Drawn from code that ran under real load.

Follow
Verified
production tested
July 15, 2026
last updated
2,398
articles · all by Naren
🔥

That's Number Theory. Mark it forged?

3 min read · try the examples if you haven't

Previous
Composite Numbers: Factorization, Primality Testing and Cryptography
7 / 9 · Number Theory
Next
Miller-Rabin Primality Test: Probabilistic Prime Detection