Finding the least common multiple of a range of numbers in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 21-Nov-2020 10:16:24
Advertisements