Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Count number of factors of a number - JavaScript
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.
Method 1: Basic Approach
This method checks every number from 1 to the given number to see if it divides evenly:
function countFactorsBasic(num) {
let count = 0;
for (let i = 1; i <= num; i++) {
if (num % i === 0) {
count++;
}
}
return count;
}
console.log(countFactorsBasic(12)); // 6
console.log(countFactorsBasic(2)); // 2
console.log(countFactorsBasic(16)); // 5
6 2 5
Method 2: Optimized Approach
This optimized version only checks up to half the number, then adds 2 to account for 1 and the number itself:
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(12)); // 6
console.log(countFactors(2)); // 2
console.log(countFactors(454)); // 4
console.log(countFactors(99)); // 6
6 2 4 6
Method 3: Most Efficient Approach
This method only checks up to the square root of the number, counting factor pairs:
function countFactorsEfficient(num) {
let count = 0;
let sqrt = Math.sqrt(num);
for (let i = 1; i <= sqrt; i++) {
if (num % i === 0) {
if (i * i === num) {
count++; // Perfect square case
} else {
count += 2; // Count both i and num/i
}
}
}
return count;
}
console.log(countFactorsEfficient(12)); // 6
console.log(countFactorsEfficient(16)); // 5 (perfect square)
console.log(countFactorsEfficient(25)); // 3 (perfect square)
6 5 3
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Basic Approach | O(n) | O(1) | Small numbers |
| Optimized Approach | O(n/2) | O(1) | Medium numbers |
| Efficient Approach | O(?n) | O(1) | Large numbers |
Conclusion
For counting factors efficiently, use the square root method as it has O(?n) time complexity. The optimized approach works well for moderate-sized numbers, while the basic method is easiest to understand for beginners.
