Menu

gitpiper

lcm javascript Code Snippet in 2023

mathalgorithmrecursionintermediate

Last Updated: 31 January 2023

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

javascript snippet similar to lcm For You in February 2023

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2023 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️