Files
30-seconds-of-code/snippets/lcm.md
Angelos Chalaris 8a6b73bd0c Update covers
2023-02-16 22:24:28 +02:00

644 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Least common multiple math,algorithm,recursion waving-over-lake 2017-12-17T17:55:51+02:00 2020-12-28T13:49:24+02:00

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