primeFactors

Medium · Number Theory · 3 test cases

Given a positive integer, return an array of its prime factors.

Examples

primeFactors(12) → [2, 2, 3]
primeFactors(84) → [2, 2, 3, 7]

Starter code

function primeFactors(n) {

}

Complexity of the optimal solution

Time O(sqrt(n)), space O(log n). The algorithm iterates up to the square root of n. The space complexity depends on the number of prime factors, which is at most O(log n) for a number n.

Solve primeFactors in the browser