We are required to write a JavaScript function that takes in an array of exactly two numbers specifying a range.
The function should then calculate the least common multiple of all the numbers within that range and return the final result.
Example
The code for this will be −
const range = [8, 3];
const gcd = (a, b) => {
return !b ? a : gcd(b, a % b);
}
const lcm = (a, b) => {
return a * (b / gcd(a,b));
};
const rangeLCM = (arr = []) => {
if(arr[0] > arr[1]) (arr = [arr[1], arr[0]]);
for(let x = result = arr[0]; x <= arr[1]; x++) {
result = lcm(x, result);
}
return result;
}
console.log(rangeLCM(range));Output
And the output in the console will be −
840