Prime factorization

Medium TimeO(√n) SpaceO(log n)

Every whole number above 1 is a product of primes in exactly one way apart from ordering, so 360 is 2 × 2 × 2 × 3 × 3 × 5. Given an integer n greater than 1, return those primes in ascending order, repeating each as many times as it divides. The factors multiply back to exactly n.

Examples

Example 1

Input
n = 360
Output
[2,2,2,3,3,5]
2 × 2 × 2 × 3 × 3 × 5 = 360, with 2 dividing three times over.

Example 2

Input
n = 97
Output
[97]
97 is prime, so it is its own only factor.

The Code

function primeFactors(n) {
  const factors = [];
  let d = 2;
  while (d * d <= n) {
    while (n % d === 0) {
      factors.push(d);
      n = n / d;
    }
    d++;
  }
  if (n > 1) factors.push(n);
  return factors;
}
primeFactors(360);
Done
Step through primeFactors(360) call by call