Store the smallest prime factor
Prepare useful witnesses for many bounded factorization queries.
Understand the idea
A prime flag says whether x is prime; SPF gives a factor to divide by. Set a number’s smallest factor only when it is first reached by a prime. Repeatedly replace x with x/spf[x] until x becomes 1.
Trace a small example
For 84, follow 84 → 42 → 21 → 7 → 1, extracting 2, 2, 3, 7. Group equal factors to recover exponents. A prime stores itself, and 1 needs no division.
Conditions and cost
Standard SPF preparation takes O(N log log N) time and O(N) space. A query uses O(log x) divisions because each factor is at least 2. Never look up x > N or divide by an uninitialized table entry.
What does SPF provide beyond a prime flag?
Turn the idea into code
Use SPF to factor 60.
Give me a hint
Continue using 2 until the remainder becomes odd.
Show the explained solution
60 → 30 → 15 → 5 → 1 extracts 2, 2, 3, 5, giving 2² × 3 × 5.
Your notes
Mark complete when you can explain it yourself.