Smallest number that is divisible by first n numbers in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number, say n. The function should find and return the smallest possible number that is exactly divisible by all numbers from 1 to n.

Example

Following is the code −

const smallestDivisible = (num) => {
   let i, n = 1;
   const largestPower = (n, num) => {
      let p, e = 2, largest = n;
      while ((p = Math.pow(n, e)) <= num) {
         largest = p;
         e += 1;
      }
      return largest;
   }
   const isPrime = n => {
      let i, num = Math.ceil(Math.sqrt(n));
      for (i = 3; i <= num; i += 2) {
         if (n % i === 0) {
            return false;
         }
      }
      return true;
   }
   for (i = 3; i <= num; i += 2) {
      if (isPrime(i)) {
         n *= largestPower(i, num);
      }
   }
   return n * largestPower(2, num);
}
console.log(smallestDivisible(20));

Output

Following is the output on console −

232792560
raja
Published on 10-Dec-2020 07:48:02
Advertisements