LCM of two numbers
Pattern: Maths basics
Find the least common multiple through the gcd, dividing before multiplying so nothing overflows.
The problem
You are given two whole numbers a and b, each from 1 up to the 32-bit limit. Return their least common multiple
(lcm): the smallest positive number that both divide exactly. For example, the lcm of 4 and 6 is 12, and the lcm of 7
and 13 is 91.
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name lcm and the limits above are this guide's own. The answer can be bigger than 32 bits, so it is returned
as a 64-bit number.
Think first
- Write the multiples of 6 (6, 12, 18, ...). Which is the first one that 4 also divides?
- Compute 4 × 6 and gcd(4, 6) × lcm(4, 6). What do you notice?
- If
aandbare both near 2 billion, cana × bfit in 32 bits?
Hints
Brute force, and why it fails
Walk through the multiples of the bigger number, max, 2 × max, 3 × max, ..., until the smaller number divides one.
That is correct, but when the two numbers share no factor the answer is their product, and you walk through min
multiples. For two large primes that is about 2 billion steps.
The key insight
The gcd and the lcm are linked: gcd × lcm = a × b. Finding the gcd takes a few dozen steps, so the lcm takes a few
dozen steps too.
Dry run
| a | 4 |
|---|---|
| b | 6 |
| x | 4 |
| y | 6 |
a = 4 and b = 6. First find their gcd with Euclid's method, on copies x = 4 and y = 6 so a and b stay unchanged.
The plan
x = a
y = b
while y != 0: # Euclid's method on copies
remainder = x mod y
x = y
y = remainder
# x is now gcd(a, b)
return (a div x) * b # divide first; multiply in 64 bits
Complexity
- Time
O(log(min(a, b)))- Space
O(1)
The work is Euclid's method plus one division and one multiplication.
Edge cases
- Equal numbers:
lcm(5, 5) = 5. - One divides the other:
lcm(3, 12) = 12. - No common factor: the lcm is the product, as in
lcm(7, 13) = 91. - 2,147,483,647 and 2,147,483,646 share no factor, so the lcm is their product, 4,611,686,011,984,936,962, which needs 64 bits.
I've built my logic, show the code
Java
class Solution {
public long lcm(int a, int b) {
int x = a;
int y = b;
while (y != 0) {
int remainder = x % y;
x = y;
y = remainder;
}
return (long) (a / x) * b;
}
}C++
class Solution {
public:
long long lcm(int a, int b) {
int x = a;
int y = b;
while (y != 0) {
int remainder = x % y;
x = y;
y = remainder;
}
return static_cast<long long>(a / x) * b;
}
};Python
class Solution:
def lcm(self, a, b):
x, y = a, b
while y != 0:
x, y = y, x % y
return (a // x) * bCommon mistakes
- Computing
a * bin 32 bits before dividing. It overflows long before the answer does. - Running Euclid's method on
aandbthemselves and then using the changed values in the formula. - Returning a 32-bit result when the true lcm needs 64 bits.