Cleaned up the current snippets for consistency and minor problems, added multiple tags to most of them, archived a few.
442 B
442 B
lcm
Returns the least common multiple of two or more numbers.
Use the greatest common divisor (GCD) formula and Math.abs() to determine the least common multiple.
The GCD formula uses recursion.
const lcm = (...arr) => {
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
const _lcm = (x, y) => x * y / gcd(x, y);
return [...arr].reduce((a, b) => _lcm(a, b));
};
lcm(12, 7); // 84
lcm(...[1, 3, 4, 5]); // 60