30秒学会 JavaScript 片段 · 2023年3月18日

30秒学会 JavaScript 片段 – Prime factors of number

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]

翻译自:https://www.30secondsofcode.org/js/s/prime-factors