How to use loops and Math.pow() Method In Javascript
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:
function isPrime(i) {
if (i == 2) return true;
for (let j = 2; j < Math.pow(i, 0.5) + 1; ++j) {
if (i % j === 0) return false;
}
return true;
}
function prime(n) {
let result = [];
for (let i = 2; i < Math.pow(n, 0.5); i++) {
if (n % i == 0 && isPrime(i)) result.push(i);
if (n % i == 0 && isPrime(n/i)) result.push(n/i);
}
return result.sort((a,b)=>a-b);
}
const num = 85;
console.log("Prime factors of " +
num + ": " + prime(num));
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