Skip to content
RSS feed tkhwang on GitHub tkhwang on Twitter

Prime Factorization in javascript

πŸ”₯ Algorithm: array return

const primeFactors = (num) => {
  const res = [];
  let prime = 2;

  while (num > 1) {
    if (num % prime === 0) {
      res.push(prime);
      num /= prime;
    } else {
      prime += 1;
    }
  }
  return res;
};
primeFactors(100);
// [2, 2, 5, 5]

πŸ”₯ Algorithm: object return

const primeFactors = (n) => {
  let counts = {};
  for (let x = 2; x * x <= n; x++) {
    while (n % x === 0) {
      counts[x] = (counts[x] || 0) + 1;
      n /= x;
    }
  }
  if (n > 1) counts[n] = (counts[n] || 0) + 1;
  return counts;
};
primeFactors(100);
// {2: 2, 5: 2}

πŸ“š References