Counting divisors of a number using JavaScript



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
Updated on: 2021-04-17T12:36:25+05:30

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements