GCD of Two Numbers (Loop) in Python

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

BeginnerLoop ProgramsExample 10 of 25
gcd-of-two-numbers-loop.py
Run in browser
1# Program to find GCD of two numbers using Euclidean algorithm
2
3a = int(input("Enter first integer: "))
4b = int(input("Enter second integer: "))
5
6while b != 0:
7 a, b = b, a % b
8
9print("GCD is", abs(a))

Output

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

What's going on

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