GCD of Two Numbers (Loop)

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

BeginnerTopic: Loop Programs
Back

Python GCD of Two Numbers (Loop) Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# 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

Understanding GCD of Two Numbers (Loop)

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents