Recursive Approach with Spread Operator
In this method, we will call the function recursively and return the output with the spread operator to get the array output.
Example:
function recursivePrime(n, d) {
if (n <= 1) return [];
if (n == 2) return [2];
flag = false;
while (n % d == 0) {
n /= d;
flag = true;
}
if (flag) return [d, ...recursivePrime(n, d + 1)];
return recursivePrime(n, d + 1);
}
const num = 85;
console.log(
"Prime factors of " +
num + ": " +
recursivePrime(num, 2)
);
Output
Prime factors of 85: 5,17
JavaScript Program to Find Prime Factors
In this article, we will see all the methods to find the prime factors of a number using JavaScript.
Methods to Find Prime Factors:
Table of Content
- Using loops and Math.pow() Method
- Recursive Approach with Spread Operator
- Sieve of Eratosthenes Algorithm