Count number of factors of a number - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number and returns the count of numbers that exactly divides the input number.

For example −

If the number is 12, then its factors are −

1, 2, 3, 4, 6, 12

Therefore, the output should be 6.

Example

Following is the code −

const num = 12;
const countFactors = num => {
   let count = 0;
   let flag = 2;
   while(flag <= num / 2){
      if(num % flag++ !== 0){
         continue;
      };
      count++;
   };
   return count + 2;
};
console.log(countFactors(num));
console.log(countFactors(2));
console.log(countFactors(454));
console.log(countFactors(99));

Output

Following is the output in the console −

6
2
4
6
raja
Published on 15-Sep-2020 15:03:47
Advertisements