Example 1 — Simple Trial
Try candidates from 2 upward while dividing n down to 1.
function printPrimeFactors(n) {
if (n <= 1) {
console.log("Enter an integer greater than 1.");
return;
}
let line = "Prime factors of " + n + ": ";
for (let i = 2; i <= n; i++) {
while (n % i === 0) {
line += i + " ";
n = Math.floor(n / i);
}
}
console.log(line.trim());
}
printPrimeFactors(84); How It Works
- Reject
n <= 1— factorization needs an integer greater than 1. - Outer loop tries each candidate
istarting at 2. - Inner
whilepeels every copy of that factor fromnwithMath.floor. - Because smaller factors are removed first, each printed
iis prime. - When
nbecomes 1, the loop ends and the factorization is complete.
