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
- For two positive numbers, GCD × LCM = a × b. So the LCM is
a * bdivided by the GCD. - For 21 and 6: the GCD is 3, so the LCM is 126 // 3 = 42.
//(floor division) keeps the result a whole number. The division is always exact here, so nothing is lost.abs()keeps the result positive for negative input.- The check for zero comes first: by convention the LCM with 0 is 0, and
math.gcd(0, 0)is 0, so the division would raise aZeroDivisionError.
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.