This post shows how to find the GCD (Greatest Common Divisor), also called HCF (Highest Common Factor), of two numbers in Python using the Euclidean algorithm.
Find GCD of two numbers in Python:
Explanation:
The Euclidean algorithm repeatedly replaces the larger number with the remainder of dividing it by the smaller number, until the remainder is 0. The last non-zero remainder is the GCD.
Python Program to Find GCD of Two Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
while b:
a, b = b, a % b
print(f"The GCD is {a}")
Output:
Enter first number: 48
Enter second number: 18
The GCD is 6
Python also has a built-in way to do this: math.gcd(a, b) from the math module — useful to know for interviews too. Practice more with our Interview Prep.
