PythonMastery

GCD of two numbers in Python

Find the greatest common divisor (GCD, also called HCF) of two numbers with Euclid's algorithm, and with the built-in math.gcd().

The greatest common divisor (GCD) of two numbers is the largest number that divides both of them with no remainder. It is also called the HCF (highest common factor). The GCD of 48 and 18 is 6.

The program

python
def gcd(a, b):
    while b != 0:
        print(f"  {a} % {b} = {a % b}")
        a, b = b, a % b
    return abs(a)


print("GCD =", gcd(48, 18))
output
  48 % 18 = 12
  18 % 12 = 6
  12 % 6 = 0
GCD = 6

How it works

This is Euclid's algorithm, one of the oldest algorithms still in use. It uses one fact: the GCD of a and b is the same as the GCD of b and the remainder a % b.

Another way: math.gcd()

The math module has this function already. It also accepts more than two numbers:

python
import math

print(math.gcd(48, 18))
print(math.gcd(17, 5))
print(math.gcd(12, 18, 30))
output
6
1
6

When the GCD is 1, as for 17 and 5, the two numbers are called coprime: they have no common divisor except 1. To find the smallest common multiple instead, see the LCM program.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Functions & Scoping