Smallest possible number divisible by all numbers from 1 to n in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number n. Our function should find and return that smallest possible number which is divisible by all numbers from 1 to n.

Example

Following is the code −

 Live Demo

const num = 11;
const smallestDivisible = (num = 1) => {
   let res = num * (num - 1) || 1;
   for (let i = num - 1; i >= 1; i--) {
      if (res % i) {
         for (let j = num - 1; j >= 1; j--) {
            if (!(i % j) && !(res % j)) {
               res = i * res / j;
               break;
            }
         }
      }
   }
   return res;
}
console.log(smallestDivisible(num));

Output

27720
raja
Published on 19-Apr-2021 10:59:36
Advertisements