Sub topic 9
From GCD to Least Common Multiple
This chapter assumes you know Euclid's algorithm from the earlier chapters, including the iterative gcd(a, b) function and the convention that gcd(0, 0) = 0. You should also be comfortable with Python's integer division // and with reading short proofs. Prime factorization appears as one way to understand the main identity. A second proof avoids it.
Once you can compute the greatest common divisor quickly, you get the least common multiple almost for free. This chapter shows why that works, how to code it so it stays exact and avoids overflow, and where people usually go wrong.
What the Least Common Multiple Is
A multiple of an integer a is any number a * k for an integer k. A common multiple of a and b is a number that is a multiple of both. The least common multiple, written lcm(a, b), is the smallest positive common multiple of two nonzero integers.
For 4 and 6, the positive multiples are:
| Number | Positive multiples |
|---|---|
| 4 | 4, 8, **12**, 16, 20, **24**, 28, ... |
| 6 | 6, **12**, 18, **24**, 30, 36, ... |
The common multiples are 12, 24, 36, and so on. The smallest is 12, so lcm(4, 6) = 12. Every other common multiple is a multiple of 12. That fact holds in general, and we prove it below.
You can find the LCM by listing multiples, but that takes up to b steps. Factoring both numbers into primes also works, but factoring large numbers is slow. The GCD gives a much better route.
The Key Identity
For any integers a and b:
lcm(a, b) * gcd(a, b) = |a * b|
So when a and b are not both zero, lcm(a, b) = |a * b| / gcd(a, b). Euclid's algorithm computes the GCD in a logarithmic number of steps, so the LCM costs one GCD plus one division and one multiplication.
Seeing It Through Prime Exponents
Write each number as a product of primes. The GCD takes the smaller exponent of each prime, and the LCM takes the larger one. For 12 and 18:
| Prime | Exponent in 12 | Exponent in 18 | min (GCD) | max (LCM) |
|---|---|---|---|---|
| 2 | 2 | 1 | 1 | 2 |
| 3 | 1 | 2 | 1 | 2 |
So gcd = 2 * 3 = 6 and lcm = 2^2 * 3^2 = 36. For any two numbers x and y, min(x, y) + max(x, y) = x + y. That makes the exponents in gcd * lcm equal to the exponents in a * b. Here, 6 * 36 = 216 = 12 * 18.
A Proof Without Factorization
Prime factorization makes the identity easy to see, but you can prove it using only what you know about the GCD. Let a and b be positive and let g = gcd(a, b). Write a = g * a' and b = g * b'. Then gcd(a', b') = 1, because any common factor d > 1 of a' and b' would make g * d a larger common divisor of a and b.
m = g * a' * b'is a common multiple. It equalsa * b'and alsob * a'.- Every common multiple is a multiple of
m. SupposeMis a common multiple. SinceadividesM, writeM = g * a' * k. Sinceb = g * b'dividesM,b'dividesa' * k. Becausegcd(a', b') = 1,b'must dividek. This step uses Euclid's lemma, which the next chapter derives from Bézout's identity. Sok = b' * j, andM = g * a' * b' * j = m * j. - So
mis the least positive common multiple, andm = g * a' * b' = (a * b) / g.
Step 2 also proves the claim from the table above: the common multiples of a and b are exactly the multiples of lcm(a, b).
Implementing It Correctly
The diagram shows the computation, including the zero check.
Here is a complete implementation:
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
def lcm(a, b):
if a == 0 or b == 0:
return 0
return abs(a // gcd(a, b) * b)
print(lcm(4, 6)) # 12
print(lcm(12, 18)) # 36
print(lcm(1071, 462)) # 23562
print(lcm(-4, 6)) # 12
print(lcm(0, 5)) # 0Trace lcm(1071, 462). Euclid's algorithm gives remainders 147, 21, and 0, so g = 21. Then 1071 // 21 = 51, and 51 * 462 = 23562. As a check, 1071 * 462 = 494802, and 494802 / 21 = 23562.
Three choices in this code matter, and each one prevents a real bug.
Choice 1: Use `//`, Not `/`
In Python 3, / always returns a float. A float has 53 bits of precision, so once values pass about 9 × 10^15 the result can be silently wrong:
import math
a, b = 2**53 + 1, 2
g = math.gcd(a, b)
float_version = a * b / g
exact_version = a // g * b
print(float_version == exact_version) # False
print(exact_version) # 18014398509481986
print(int(float_version)) # 18014398509481984The float version is off by 2, and nothing raises an error. Always use integer division.
Choice 2: Divide Before You Multiply
The formula a * b // g gives the right answer in Python, because Python integers have arbitrary size. In languages with fixed-width integers, such as C, Java, Rust, or Go, the product a * b can overflow even when the final LCM fits easily. Dividing first keeps the intermediate value no larger than the result:
INT64_MAX = 2**63 - 1
a, b = 3_000_000_000, 6_000_000_000
g = 3_000_000_000 # gcd(a, b)
print(a * b > INT64_MAX) # True: the product would overflow int64
print(a // g * b) # 6000000000
print(a // g * b <= INT64_MAX) # True: the result fitsThe division a // g is always exact, because g divides a by definition. Dividing first therefore loses nothing. The result can still overflow if the LCM itself is too large for the type, but then no ordering of the operations would help.
Choice 3: Handle Zero Explicitly
If both inputs are zero, gcd(0, 0) = 0, and dividing by it raises ZeroDivisionError. Mathematically, the only common multiple of 0 and any b is 0, so the usual convention is lcm(a, 0) = 0. Python's math.lcm and most libraries follow it. Checking for zero first gives that answer and also avoids the division.
Negative Inputs
The LCM is defined as a nonnegative value, like the GCD. The abs around the result handles signs: lcm(-4, 6) and lcm(-4, -6) both return 12. With negative a, the expression a // g is still exact because g divides a, so floor division causes no rounding.
More Than Two Numbers
The LCM is associative: lcm(a, b, c) = lcm(lcm(a, b), c). This follows from the prime-exponent view, because the maximum of three exponents is the maximum of the first two, compared with the third. So you can fold lcm over a list:
from functools import reduce
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
def lcm(a, b):
if a == 0 or b == 0:
return 0
return abs(a // gcd(a, b) * b)
def lcm_all(numbers):
return reduce(lcm, numbers, 1)
print(lcm_all(range(1, 11))) # 2520
print(lcm_all([4, 6, 10])) # 60
print(lcm_all([4, 0, 10])) # 0
print(lcm_all([])) # 1The starting value 1 is the identity for LCM, because lcm(1, x) = |x|. That makes the LCM of an empty list equal to 1. The GCD works the same way with identity 0, because gcd(0, x) = |x|.
Do not try to extend the pairwise identity to three numbers as lcm(a, b, c) = a * b * c / gcd(a, b, c). It fails for (2, 4, 8): the formula gives 64 / 2 = 32, but the true LCM is 8.
Using the Standard Library
In production Python, use the built-ins:
import math
print(math.gcd(1071, 462)) # 21
print(math.lcm(4, 6)) # 12, available since Python 3.9
print(math.lcm(4, 6, 10)) # 60, accepts any number of arguments
print(math.lcm(-4, 6)) # 12
print(math.lcm(0, 7)) # 0
print(math.lcm()) # 1math.gcd has accepted more than two arguments since Python 3.9, and math.lcm was added in the same release. On Python 3.8 or earlier, use the hand-written lcm above. Both functions are implemented in C and are faster than a Python loop.
Where the LCM Shows Up
Adding fractions. To compute 1/12 + 5/18, use the least common denominator, lcm(12, 18) = 36. Then 3/36 + 10/36 = 13/36. Multiplying the denominators also works, giving 216, but then you have to reduce the result afterwards. Python's fractions.Fraction uses GCDs internally to keep results in lowest terms.
Repeating events. Suppose one bus leaves every 12 minutes and another every 18 minutes, and they leave together now. They next leave together after lcm(12, 18) = 36 minutes. The same reasoning gives the period of meshing gears, of overlapping cron schedules, and of combined periodic signals.
Combining cycles in algorithms. If a permutation splits into cycles of lengths 3, 4, and 6, applying it repeatedly returns everything to the start after lcm(3, 4, 6) = 12 applications.
Common Errors at a Glance
| Mistake | Symptom | Fix |
|---|---|---|
| `a * b / gcd(a, b)` | Float result, silently wrong above about 2^53 | Use `//` |
| `a * b // gcd(a, b)` in C or Java | Overflow when `a * b` exceeds the type | Compute `a / g * b` |
| No zero check | `ZeroDivisionError` for `lcm(0, 0)` | Return 0 if either input is 0 |
| No `abs` | Negative LCM for mixed signs | Wrap the result in `abs` |
| `abc / gcd(a, b, c)` for three numbers | Wrong answer, such as 32 instead of 8 for (2, 4, 8) | Fold pairwise with `reduce` |
Exercise
Use the GCD to compute lcm(84, 120). Show the Euclid steps for the GCD and the dividing-first computation.
Show answer
Euclid's algorithm gives 120 mod 84 = 36, then 84 mod 36 = 12, then 36 mod 12 = 0, so gcd = 12. Then 84 // 12 = 7, and 7 120 = 840. Check: 840 12 = 10080 = 84 * 120.
Exercise
Prove that lcm(a, b) = |a * b| exactly when gcd(a, b) = 1, for nonzero a and b.
Show answer
From lcm(a, b) gcd(a, b) = |a b|, with both sides positive, lcm(a, b) = |a * b| holds exactly when gcd(a, b) = 1.
Exercise
A colleague writes def lcm(a, b): return a * b // math.gcd(a, b). Name two inputs or situations where it misbehaves, and explain why.
Show answer
First, lcm(0, 0) raises ZeroDivisionError because math.gcd(0, 0) is 0. Second, lcm(-4, 6) returns -12 instead of 12, because nothing takes the absolute value. A third problem appears if the code is ported to a fixed-width language: a * b can overflow even when the LCM fits. In Python itself the result is exact for nonzero positive inputs.
Exercise
Without a computer, find lcm(1, 2, ..., 10) by taking the highest power of each prime that is at most 10.
Show answer
The highest prime powers up to 10 are 2^3 = 8, 3^2 = 9, 5, and 7. Their product is 8 9 5 * 7 = 2520.