Counting divisors of a number using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number and returns the count of its divisor.

Input

const num = 30;

Output

const output = 8;

Because the divisors are −

1, 2, 3, 5, 6, 10, 15, 30

Example

Following is the code −

 Live Demo

const num = 30;
const countDivisors = (num = 1) => {
   if (num === 1) return num
      let divArr = [[2, 0]]
      let div = divArr[0][0]
   while (num > 1) {
      if (num % div === 0) {
         for (let i = 0; divArr.length; i++) {
            if (divArr[i][0] === div) {
               divArr[i][1] += 1
               break
            } else {
               if (i === divArr.length - 1) {
                  divArr.push([div, 1])
                  break
               }
            }
         }
         num /= div
      } else {
         div += 1
      }
   }
   for (let i = 0; i < divArr.length; i++) {
      num *= divArr[i][1] + 1
   }
   return num
}
console.log(countDivisors(num));

Output

8
raja
Published on 17-Apr-2021 11:48:48
Advertisements