Optimised Approach
In this method, we will iterate only up to the square root of the number and add both the divisor and its complement (the number divided by the divisor) to the result array. This approach is more efficient than the naive approach, especially for large numbers.
Example:
function optimizedDivisors(n) {
let result = [];
for (let i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
result.push(i);
if (i !== n / i) {
result.push(n / i);
}
}
}
return result.sort((a, b) => a - b);
}
const num = 90;
console.log("All divisors of " + num + ": " + optimizedDivisors(num));
Output
All divisors of 90: 1,2,3,5,6,9,10,15,18,30,45,90
JavaScript Program to Find All Divisors of a Number
In this article, we will demonstrate different approaches to writing a JavaScript Program to Find all Divisors of a Number. We will have an input number and print all the divisors of that number in the form of a resultant array.
Contact Us