JavaScript Program to Find All Factors of a Natural Number
Finding all factors of a natural number is a common task in programming and mathematics. A factor of a number is an integer that can be multiplied by another integer to produce the original number. In this article, we will discuss various approaches to finding all factors of a natural number using JavaScript.
Find All Factors of a Natural Number using for Loop
The simplest way to find all factors of a number is to iterate from 1 to the number itself and check if the number is divisible by the current iteration index. If it is, then the index is a factor of the number.
Example:
Javascript
function findFactors(n) { const factors = []; for (let i = 1; i <= n; i++) { if (n % i === 0) { factors.push(i); } } return factors; } console.log(findFactors(12)); |
[ 1, 2, 3, 4, 6, 12 ]
Find All Factors of a Natural Number using Optimized Approach
We can optimize the above approach by iterating only up to the square root of the number. This is because if n
is a factor of the number, then num/n
is also a factor. However, we need to be careful to avoid duplicate factors.
Example:
Javascript
function findFactors(num) { let factors = []; for (let i = 1; i <= Math.sqrt(num); i++) { if (num % i === 0) { factors.push(i); if (i !== num / i) { factors.push(num / i); } } } return factors.sort((a, b) => a - b); } console.log(findFactors(12)); |
[ 1, 2, 3, 4, 6, 12 ]
Find All Factors of a Natural Number using Recursion
We can also use recursion to find the factors of a number. This approach is not the most efficient but can be useful in understanding recursive algorithms.
Javascript
function findFactors(num, current = 1, factors = []) { if (current > num) { return factors; } if (num % current === 0) { factors.push(current); } return findFactors(num, current + 1, factors); } console.log(findFactors(12)); |
[ 1, 2, 3, 4, 6, 12 ]
Contact Us