Prime Factorization
Basic Math
📋 Problem Statement
Given an integer , return its prime factorization as a list of prime factors. For example, , so the output is [2, 2, 3]. returns an empty list.
💡 Intuition
Repeatedly divide by the smallest possible prime factor. Start with 2 (to handle all even factors), then check only odd numbers from 3 to . If after the loop, the remaining value is itself a prime factor (the largest one).
🔧 Approach
- Initialize an empty list
factors. - While is divisible by 2, append 2 and divide by 2.
- For odd divisors up to : while is divisible by , append and divide.
- If after the loop, is a prime — append it.
⚡ Complexity Analysis
Time
for the trial division loop
Space
— constant extra space (excluding the output list)
⚠️ Common Mistakes
- Only dividing by each factor once instead of looping (misses repeated factors, e.g.,
12 = 2 × 2 × 3) - Not handling the "remaining prime" case after the loop — e.g.,
14 = 2 × 7; after dividing by 2,n = 7 > 1, so 7 must be appended - Checking only up to instead of dynamically comparing to (the latter is correct since shrinks)
🎯 Final Thoughts
Prime factorization underlies RSA encryption: factoring a large number is computationally infeasible for huge primes, while multiplying them is easy. The "remaining prime" optimization after the loop is elegant — it's the key insight that keeps this solution correct and .