Algorithm LogbookAlgorithm Logbook

Prime Factorization

Basic Math

📋 Problem Statement

Given an integer NN, return its prime factorization as a list of prime factors. For example, 12=2×2×312 = 2 \times 2 \times 3, so the output is [2, 2, 3]. N=1N = 1 returns an empty list.

💡 Intuition

Repeatedly divide NN by the smallest possible prime factor. Start with 2 (to handle all even factors), then check only odd numbers from 3 to N\sqrt{N}. If N>1N > 1 after the loop, the remaining value is itself a prime factor (the largest one).

🔧 Approach

  1. Initialize an empty list factors.
  2. While NN is divisible by 2, append 2 and divide NN by 2.
  3. For odd divisors i=3,5,7,i = 3, 5, 7, \ldots up to N\sqrt{N}: while NN is divisible by ii, append ii and divide.
  4. If N>1N > 1 after the loop, NN is a prime — append it.

Complexity Analysis

Time

O(N)O(\sqrt{N}) for the trial division loop

Space

O(1)O(1) — 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 original N\sqrt{\text{original } N} instead of dynamically comparing to i2ni^2 \leq n (the latter is correct since nn shrinks)

🎯 Final Thoughts

Prime factorization underlies RSA encryption: factoring a large number N=p×qN = p \times q 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 O(N)O(\sqrt{N}).