Introduction
In this lab, we will explore how to calculate the least common multiple of two or more numbers using JavaScript. We will 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, which we will implement in our code.
Calculating Least Common Multiple
To calculate the least common multiple of two or more numbers, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - 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.
- Implement the following code in JavaScript:
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));
};
Example usage:
lcm(12, 7); // 84
lcm(...[1, 3, 4, 5]); // 60
Summary
Congratulations! You have completed the Least Common Multiple lab. You can practice more labs in LabEx to improve your skills.