PythonMastery

LCM of two numbers in Python

Find the least common multiple (LCM) of two numbers from their GCD, handle zero, and use math.lcm() for two or more numbers.

The least common multiple (LCM) of two numbers is the smallest positive number that both of them divide into. The LCM of 4 and 6 is 12. It is what you need to add fractions like 1/4 + 1/6.

The program

python
import math


def lcm(a, b):
    if a == 0 or b == 0:
        return 0
    return abs(a * b) // math.gcd(a, b)


print("LCM of 4 and 6 =", lcm(4, 6))
print("LCM of 21 and 6 =", lcm(21, 6))
print("LCM of 7 and 5 =", lcm(7, 5))
output
LCM of 4 and 6 = 12
LCM of 21 and 6 = 42
LCM of 7 and 5 = 35

How it works

The GCD program shows how the GCD itself is calculated.

Another way: math.lcm()

Python 3.9 added math.lcm(). It accepts any number of values:

python
import math

print(math.lcm(4, 6))
print(math.lcm(4, 6, 10))
print(math.lcm(0, 5))
output
12
60
0

The LCM of 4, 6 and 10 is 60: buses that leave every 4, 6 and 10 minutes all leave together again after 60 minutes.

Learn the idea: Functions & Scoping, Operators & Expressions