Least common multiple

JavaScript, Math, Algorithm, Recursion · Dec 28, 2020

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

More like this

  • Greatest common divisor

    Calculates the greatest common divisor between two or more numbers/arrays.

    JavaScript, Math · Dec 29, 2020

  • Euclidean distance

    Calculates the distance between two points in any number of dimensions.

    JavaScript, Math · Dec 28, 2020

  • Factorial of number

    Calculates the factorial of a number.

    JavaScript, Math · Dec 28, 2020