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.
Methods to Find All Divisors of a Number
- Naive Approach
- Recursive Approach
Method 1: Naive Approach
In this method, we will use a JavaScript loop to iterate the possible factors and Math.pow() method to get the square root of the number. Instead of Math.pow() method, we can also use Math.sqrt() or i*i < n condition.
Example:
Javascript
function prime(n) { Â Â Â Â let result = [1,n]; Â Â Â Â for (let i = 2; i < Math.pow(n, 0.5); i++) { Â Â Â Â Â Â Â Â if (n % i == 0) { Â Â Â Â Â Â Â Â Â Â Â Â result.push(i); Â Â Â Â Â Â Â Â Â Â Â Â result.push(n / i); Â Â Â Â Â Â Â Â } Â Â Â Â } Â Â Â Â return result.sort((a, b) => a - b); } Â Â const num = 90; console.log("Prime factors of " +Â Â Â Â Â num + ": " + prime(num)); |
Output
Prime factors of 90: 1,2,3,5,6,9,10,15,18,30,45,90
Method 2: Recursive Approach
In this method, we will call the function recursively and return the output with the spread operator to get the array output.
Example:
Javascript
function recursiveFactor(n, d) { Â Â Â Â if (n < 1) return [];Â Â Â Â Â Â Â Â if (n == 1) return [1]; Â Â Â Â if (n == 2) return [1,2]; Â Â Â Â if(n/d<2) Â Â Â Â return [n]; Â Â Â Â if (n % d == 0) return [d, ...recursiveFactor(n, d + 1)]; Â Â Â Â return recursiveFactor(n, d + 1); } Â Â const num = 85; console.log( Â Â Â Â "All factors of " + Â Â Â Â Â Â Â Â num + ": " + Â Â Â Â Â Â Â Â recursiveFactor(num, 1) ); |
Output
All factors of 85: 1,5,17,85
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!


