Python Program for Extended Euclidean Algorithms (original) (raw)

Last Updated : 29 Oct, 2025

Given two numbers a and b, the task is to find their Extended GCD, i.e., the greatest common divisor g, and integers x and y such that: ax+by = g. This is known as Bézout’s identity, and it’s useful for solving linear Diophantine equations and finding modular inverses.

Let’s explore different ways to find the Extended GCD in Python.

Using Iterative Extended Euclidean Algorithm

This approach uses a loop to calculate both gcd and coefficients x, y such that ax + by = gcd(a, b). It avoids recursion stack usage and is memory-efficient.

Python `

a, b = 35, 15 x0, x1, y0, y1 = 1, 0, 0, 1

while b: q = a // b a, b = b, a % b x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1

print("GCD is", a) print("x =", x0, ", y =", y0)

`

Output

GCD is 5 x = 1 , y = -2

**Explanation:

Using Recursive Extended Euclidean Algorithm

This is the traditional recursive approach that returns gcd, x, and y. It works by breaking down the problem recursively until the base case is reached.

Python `

def gcdExtended(a, b): if a == 0: return b, 0, 1 gcd, x1, y1 = gcdExtended(b % a, a) x = y1 - (b // a) * x1 y = x1 return gcd, x, y

a, b = 35, 15 g, x, y = gcdExtended(a, b) print("GCD is", g) print("x =", x, ", y =", y)

`

Output

GCD is 5 x = 1 , y = -2

**Explanation:

Using Matrix Representation

This approach represents the coefficient updates as matrix multiplications, which can be useful for understanding and debugging iterative updates.

Python `

a, b = 35, 15 x, y, u, v = 0, 1, 1, 0

while a != 0: q, r = divmod(b, a) b, a = a, r x, u = u - q * x, x y, v = v - q * y, y

print("GCD is", b) print("x =", u, ", y =", v)

`

Output

GCD is 5 x = -2 , y = 1

**Explanation:

Using Built-in math.gcd()

Although this function doesn’t return the coefficients x and y, it’s the fastest way to get the GCD itself. It can serve as a quick validation check.

Python `

import math a, b = 35, 15 print("GCD is", math.gcd(a, b))

`

**Explanation: math.gcd(a, b) efficiently computes the greatest common divisor using the Euclidean algorithm internally.

Please refer complete article on Basic and Extended Euclidean algorithms for more details!