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 browser1# Program to find GCD of two numbers using Euclidean algorithm23a = int(input("Enter first integer: "))4b = int(input("Enter second integer: "))56while b != 0:7 a, b = b, a % b89print("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.