# Counting divisors of a number using JavaScript

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

## 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 17-Apr-2021 12:36:25