Python Program for Basic Euclidean Algorithms
Given two numbers a and b, the task is to find their greatest common divisor (GCD), which is the largest number that divides both a and b completely. For example:
Input: a = 10, b = 15 -> Output: 5
Input: a = 31, b = 2 -> Output: 1
Let’s explore different methods to find the GCD in Python.
Using math.gcd()
The math module provides a built-in gcd() function that internally implements the optimized Euclidean algorithm. This is the most efficient and pythonic way to find the GCD.
import math
a, b = 10, 15
print("GCD is", math.gcd(a, b))
Output
GCD is 5
Explanation: math.gcd(a, b) directly returns the greatest common divisor of the two numbers.
Using Iterative Euclidean Algorithm
This approach repeatedly replaces the larger number with the remainder until one becomes zero. The non-zero number left is the GCD.
a, b = 10, 15
while b:
a, b = b, a % b
print("GCD is", a)
Output
GCD is 5
Explanation:
- The loop continues until b becomes zero.
- In each iteration, a is replaced with b, and b with a % b.
- Once b is zero, a holds the GCD.
Using Recursive Euclidean Algorithm
This is the traditional recursive form of the algorithm. It calls itself repeatedly by swapping a and b % a until a becomes zero.
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
a, b = 10, 15
print("GCD is", gcd(a, b))
Output
GCD is 5
Explanation:
- The function keeps calling itself with the remainder until the base case (a == 0) is reached.
- The value of b at that point is the greatest common divisor.
Using Subtraction-based Euclidean Algorithm
This method repeatedly subtracts the smaller number from the larger until both become equal.
a, b = 10, 15
while a != b:
if a > b:
a -= b
else:
b -= a
print("GCD is", a)
Output
GCD is 5
Explanation:
- The larger number is reduced by the smaller in each step.
- When both numbers become equal, that value is the GCD.
Please refer complete article on Basic and Extended Euclidean algorithms for more details!