GCD of Two Numbers (Loop)

Compute the greatest common divisor (GCD) of two integers using the Euclidean algorithm.

PythonBeginner
Python
# Program to find GCD of two numbers using Euclidean algorithm

a = int(input("Enter first integer: "))
b = int(input("Enter second integer: "))

while b != 0:
    a, b = b, a % b

print("GCD is", abs(a))

Output

Enter first integer: 54
Enter second integer: 24
GCD is 6

We repeatedly replace (a, b) with (b, a % b) until b becomes 0; the remaining a is the GCD.