![]() |
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 NumberMethod 1: Naive ApproachIn 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:
Output Prime factors of 90: 1,2,3,5,6,9,10,15,18,30,45,90 Method 2: Recursive ApproachIn this method, we will call the function recursively and return the output with the spread operator to get the array output. Example:
Output All factors of 85: 1,5,17,85 Method 3: Optimised ApproachIn 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:
Output All divisors of 90: 1,2,3,5,6,9,10,15,18,30,45,90 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |