Files
30-seconds-of-code/snippets/lcm.md
Isabelle Viktoria Maciohsek 81e37d20c0 Consistent whitespace
2020-11-03 21:46:13 +02:00

529 B

title, tags
title tags
lcm math,recursion,intermediate

Calculates the least common multiple of two or more numbers.

  • Use the greatest common divisor (GCD) formula and the fact that lcm(x, y) = x * y / gcd(x, y) 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