Smallest Common Multiple of an array of numbers in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of two numbers that specify a range. We are required to write a function that finds the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters.

The range will be an array of two numbers that will not necessarily be in numerical order.

For example, if given [1, 3], then we are required to find the smallest common multiple of both 1 and 3 that is also evenly divisible by all numbers between 1 and 3. The answer here would be 6.

Example

The code for this will be −

const range = [1, 12];
const smallestCommon = (array = []) => {
   arr = array.slice().sort((a, b) => a − b);
   let result = [];
   for(let i = arr[0]; i <= arr[1]; i++){
      result.push(i);
   };
   let i = 1;
   let res;
   while(result.every(item=>res%item==0)==false){
      i++;
      res = arr[1]*i;
   }
   return res;
}
console.log(smallestCommon(range));

Output

And the output in the console will be −

27720
raja
Published on 21-Nov-2020 15:02:01
Advertisements