Least common multiple
Algorithm · Stretch
Step through it: Number Theory pattern
Step 1 of 5
Goal: the greatest common divisor of 48 and 18. Key fact: the answer stays the same if you replace (a, b) with (b, the remainder of a ÷ b). The numbers shrink quickly.
Step 2 of 5
48 ÷ 18 leaves remainder 12, so carry on with (18, 12).
Step 3 of 5
18 ÷ 12 leaves 6: carry on with (12, 6).
Step 4 of 5
12 ÷ 6 leaves 0, so stop: the answer is 6. Remainders shrink fast, so only a few steps (O(log n)). The least common multiple follows: lcm = a × b ÷ gcd. These are number theory tools.
Step 5 of 5
Your turn.
In arithmetic and number theory, the least common multiple,
lowest common multiple, or smallest common multiple of
two integers a and b, usually denoted by LCM(a, b), is
the smallest positive integer that is divisible by
both a and b. Since division of integers by zero is
undefined, this definition has meaning only if a and b are
both different from zero. However, some authors define lcm(a,0)
as 0 for all a, which is the result of taking the lcm
to be the least upper bound in the lattice of divisibility.
Example
What is the LCM of 4 and 6?
Multiples of 4 are:
4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, ...and the multiples of 6 are:
6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, ...Common multiples of 4 and 6 are simply the numbers
that are in both lists:
12, 24, 36, 48, 60, 72, ....So, from this list of the first few common multiples of
the numbers 4 and 6, their least common multiple is 12.
Computing the least common multiple
The following formula reduces the problem of computing the least common multiple to the problem of computing the greatest common divisor (GCD), also known as the greatest common factor:
lcm(a, b) = |a * b| / gcd(a, b)A Venn diagram showing the least common multiples of
combinations of 2, 3, 4, 5 and 7 (6 is skipped as
it is 2 × 3, both of which are already represented).
For example, a card game which requires its cards to be
divided equally among up to 5 players requires at least 60
cards, the number at the intersection of the 2, 3, 4
and 5 sets, but not the 7 set.
Code
import euclideanAlgorithm from '../euclidean-algorithm/euclideanAlgorithm';
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
export default function leastCommonMultiple(a, b) {
return ((a === 0) || (b === 0)) ? 0 : Math.abs(a * b) / euclideanAlgorithm(a, b);
}References
Practice
Number Theory
- Greatest Common Divisor of StringsEasy
- Ugly NumberEasy
- Happy NumberEasy
- Plus OneEasy
- Add BinaryEasy
- Excel Sheet Column NumberEasy
- Count PrimesMedium
- Pow(x, n)Medium
- Factorial Trailing ZeroesMedium
- Ugly Number IIMedium
- Multiply StringsMedium
- Divide Two IntegersMedium
- Water and Jug ProblemMedium
- Super PowMedium
- Largest Component Size by Common FactorHard
Spotted a mistake or something unclear? Report it on GitHub.