Files
30-seconds-of-code/snippets/primeFactors.md
Isabelle Viktoria Maciohsek 8bf67754ce Make expertise a field
2022-03-01 20:21:45 +02:00

684 B

title, tags, expertise, firstSeen, lastUpdated
title tags expertise firstSeen lastUpdated
Prime factors of number math,algorithm beginner 2020-12-28T13:11:01+02:00 2020-12-28T13:11:01+02:00

Finds the prime factors of a given number using the trial division algorithm.

  • Use a while loop to iterate over all possible prime factors, starting with 2.
  • If the current factor, f, exactly divides n, add f to the factors array and divide n by f. Otherwise, increment f by one.
const primeFactors = n => {
  let a = [],
    f = 2;
  while (n > 1) {
    if (n % f === 0) {
      a.push(f);
      n /= f;
    } else {
      f++;
    }
  }
  return a;
};
primeFactors(147); // [3, 7, 7]