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.
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.
a,b=35,15x0,x1,y0,y1=1,0,0,1whileb:q=a//ba,b=b,a%bx0,x1=x1,x0-q*x1y0,y1=y1,y0-q*y1print("GCD is",a)print("x =",x0,", y =",y0)
GCD is 5x = 1 , y = -2
Explanation:
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.
defgcdExtended(a,b):ifa==0:returnb,0,1gcd,x1,y1=gcdExtended(b%a,a)x=y1-(b//a)*x1y=x1returngcd,x,ya,b=35,15g,x,y=gcdExtended(a,b)print("GCD is",g)print("x =",x,", y =",y)
This approach represents the coefficient updates as matrix multiplications, which can be useful for understanding and debugging iterative updates.
a,b=35,15x,y,u,v=0,1,1,0whilea!=0:q,r=divmod(b,a)b,a=a,rx,u=u-q*x,xy,v=v-q*y,yprint("GCD is",b)print("x =",u,", y =",v)
GCD is 5x = -2 , y = 1
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.
importmatha,b=35,15print("GCD is",math.gcd(a,b))
GCD is 5
Explanation:math.gcd(a, b) efficiently computes the greatest common divisor using the Euclidean algorithm internally.
Please refer complete article onBasic and Extended Euclidean algorithms for more details!
K
Python Introduction
Input and Output in Python
Python Variables
Python Operators
Python Keywords
Python Data Types
Conditional Statements in Python
Loops in Python - For, While and Nested Loops
Python Functions
Recursion in Python
Python Lambda Functions
Python String
Python Lists
Python Tuples
Python Dictionary
Python Sets
Python Arrays
List Comprehension in Python
Python OOP Concepts
Python Exception Handling
File Handling in Python
Python Database Tutorial
Python MongoDB Tutorial
Python MySQL
Python Packages
Python Modules
Python DSA Libraries
List of Python GUI Library and Packages
NumPy Tutorial - Python Library
Pandas Tutorial
Matplotlib Tutorial
Python Seaborn Tutorial
StatsModel Library - Tutorial
Learning Model Building in Scikit-learn
TensorFlow Tutorial
PyTorch Tutorial
Flask Tutorial
Django Tutorial | Learn Django Framework
Django ORM - Inserting, Updating & Deleting Data
Templating With Jinja2 in Flask
Django Templates
Python | Build a REST API using Flask
How to Create a basic API using Django Rest Framework ?
Python Quiz
Python Coding Practice
Python Interview Questions and Answers