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


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

Updated on: 19-Apr-2021

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements