Calculate Least Common of a Range in JavaScript



We are required to write a function that takes in an array of two numbers a and b (a >= b) and returns the least common multiple of all the numbers between [a, b].

Approach

We will first write a basic function that calculates the least common multiple of two numbers, once we have that we will recursively call it over the numbers that fall between [a, b] and finally return the result.

Example

const lcm = (a, b) => {
   let min = Math.min(a, b);
   while(min >= 2){
      if(a % min === 0 && b % min === 0){
         return (a*b)/min;
      };
      min--;
   };
   return (a*b);
};
const leastCommonMultipleInRange = (arr, len = arr[0], res = 1) => {
   if(len <= arr[1]){
      return leastCommonMultipleInRange(arr, len+1, lcm(res, len));
   };
   return res;
};
console.log(leastCommonMultipleInRange([6, 8]));
console.log(leastCommonMultipleInRange([6, 18]));
console.log(leastCommonMultipleInRange([1, 8]));
console.log(leastCommonMultipleInRange([10, 25]));

Output

The output in the console will be −

168
12252240
840
26771144400
Updated on: 2020-08-25T06:49:34+05:30

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements