Algorithms · Visualized
Number Theory: LCM
Number Theory
Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.
The least common multiple of two numbers is the smallest number divisible by both. Time: O(log(min(a,b))) — dominated by the GCD computation average, O(log(min(a,b))) worst; space: O(1).
Big-O: GCD O(log min(a,b)); sieve O(n log log n).
LCM (Least Common Multiple)
Number TheoryThe least common multiple of two numbers is the smallest number divisible by both. Rather than searching multiples one by one, it can be computed directly from the GCD using the relationship: LCM(a, b) = (a × b) / GCD(a, b).
How LCM Works
- Compute the GCD of the two numbers using the Euclidean algorithm.
- Multiply the two original numbers together.
- Divide that product by the GCD computed in step 1.
- The result is the least common multiple.
- (To avoid overflow with large numbers, it's common to divide by the GCD first, then multiply: (a / GCD) × b.)
LCM Worked Example
Input: {a: 4, b: 6}
GCD(4,6) = 2. LCM = (4 × 6) / 2 = 24 / 2 = 12. Check: 12 is divisible by both 4 and 6, and it's the smallest such number.
def lcm(a, b):
return a * b // gcd(a, b)Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
LCM Time & Space Complexity
When to Use LCM
- Scheduling problems: finding when repeating events next align (e.g. two buses on different cycles arriving together).
- Adding fractions with different denominators requires finding their LCM as a common denominator.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.