Skip to content
Devtoolry

Numbers · beginner

Python Program to Find the GCD (HCF) of Two Numbers

Find the greatest common divisor (GCD, also called HCF) of two numbers in Python with Euclid's algorithm and math.gcd(), and use it to get the LCM.

The greatest common divisor (GCD), also called the highest common factor (HCF), is the largest number that divides both numbers without a remainder. The GCD of 48 and 18 is 6. It is used to simplify fractions: 48/18 = 8/3.

Euclid's algorithm, more than 2,000 years old, finds it quickly: the GCD of a and b is the same as the GCD of b and a % b, and when the remainder reaches 0 the other number is the answer.

The program

Python
def gcd(a, b):
    while b:
        a, b = b, a % b
    return abs(a)

print(gcd(48, 18))
print(gcd(17, 5))
print(gcd(0, 9))

a, b = 12, 18
print("LCM:", a * b // gcd(a, b))
Output
6
1
9
LCM: 36

How it works

  1. while b keeps going as long as b is not 0.
  2. Each pass replaces the pair (a, b) with (b, a % b): (48, 18) → (18, 12) → (12, 6) → (6, 0).
  3. When b reaches 0, a holds the GCD. abs() makes the result positive for negative inputs.
  4. The least common multiple follows from the GCD: lcm(a, b) = a × b ÷ gcd(a, b). // keeps it an integer.

Watch it run line by line

Step through gcd(48, 18) and watch the pair a, b change on every pass of the loop: (18, 12), (12, 6), (6, 0). Only four steps, even though the numbers have many divisors.

“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: With the math module

math.gcd() and math.lcm() (Python 3.9+) accept any number of arguments and are what you should use in real code.

Python
import math

print(math.gcd(48, 18))
print(math.gcd(12, 18, 30))
print(math.lcm(4, 6, 10))
Output
6
6
60

Common mistakes

  • Looping over every number from 1 to min(a, b) to find common divisors: correct but slow for big numbers.
  • Computing the LCM with / instead of //, which gives a float such as 36.0.
  • Writing a = b and b = a % b on separate lines: the second line then uses the new a.

Try it yourself

  • Simplify the fraction 84/126 using the GCD.
  • Write a recursive version: gcd(a, b) = a if b == 0 else gcd(b, a % b).

Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 Python examples, or write your own program in the online Python Compiler.