# 如何在JavaScript中找到整数的素因数？ [英] How can I find the prime factors of an integer in JavaScript?

### 问题描述

``````//integer is the value for which we are finding prime factors
var integer = 13195;

var primeArray = [];

//find divisors starting with 2

for (i = 2; i < integer/2; i++) {
if (integer % i == 0) {

//check if divisor is prime
for (var j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
} else {
isPrime = true;
}
}

//if divisor is prime

if (isPrime == true) {
//divide integer by prime factor & factor store in array primeArray
integer /= i
primeArray.push(i);
}
}
}

for (var k = 0; k < primeArray.length; k++) {
console.log(primeArray[k]);
}``````

### 推荐答案

``````function primeFactors(n) {
const factors = [];
let divisor = 2;

while (n >= 2) {
if (n % divisor == 0) {
factors.push(divisor);
n = n / divisor;
} else {
divisor++;
}
}
return factors;
}

const randomNumber = Math.floor(Math.random() * 10000);
console.log('Prime factors of', randomNumber + ':', primeFactors(randomNumber).join(' '))``````