Search code examples
javascriptfor-loopprimes

How can I find the prime factors of an integer in JavaScript?


I was trying to find the prime factors of a number, recorded below as 'integer' using a for loop in javascript. I can't seem to get it working and I'm not sure whether it's my JavaScript or my calculation logic.

//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]);
}


Solution

  • Here is an answer with O(N) complexity.

    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(' '))

    You can filter for duplicates as you please!