![]() |
VOOZH | about |
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.
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.
GCD is 5
Explanation: math.gcd(a, b) directly returns the greatest common divisor of the two numbers.
This approach repeatedly replaces the larger number with the remainder until one becomes zero. The non-zero number left is the GCD.
GCD is 5
Explanation:
This is the traditional recursive form of the algorithm. It calls itself repeatedly by swapping a and b % a until a becomes zero.
GCD is 5
Explanation:
This method repeatedly subtracts the smaller number from the larger until both become equal.
GCD is 5
Explanation:
Please refer complete article on Basic and Extended Euclidean algorithms for more details!