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
1# 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.
After this program
If the idea is still fuzzy, read Day 9: Loops and Iteration in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 loop programs, or see every topic on Python exercises.