Smallest Value After Replacing With Sum of Prime Factors - Problem

You are given a positive integer n. Your task is to repeatedly replace n with the sum of its prime factors until you reach the smallest possible value.

Important note: If a prime factor divides n multiple times, it should be included in the sum as many times as it divides n. For example, if n = 12 = 2² × 3, then the sum of prime factors is 2 + 2 + 3 = 7.

The process continues until n becomes a prime number (which cannot be reduced further) or reaches a stable value. Return the smallest value that n will eventually reach.

Example: Starting with n = 15:
15 = 3 × 5 → sum = 3 + 5 = 8
8 = 2³ → sum = 2 + 2 + 2 = 6
6 = 2 × 3 → sum = 2 + 3 = 5
5 is prime, so we stop.
The answer is 5.

Input & Output

example_1.py — Small Composite Number
$ Input: n = 15
Output: 5
💡 Note: 15 = 3 × 5, sum = 8. Then 8 = 2³, sum = 6. Then 6 = 2 × 3, sum = 5. Since 5 is prime, we stop.
example_2.py — Perfect Square
$ Input: n = 4
Output: 4
💡 Note: 4 = 2², sum = 2 + 2 = 4. Since we get the same number, we've reached a fixed point and stop.
example_3.py — Prime Number
$ Input: n = 2
Output: 2
💡 Note: 2 is already prime, so no transformation is needed. The answer is 2.

Visualization

Tap to expand
153582226235PRIME!3+5=82+2+2=62+3=5
Understanding the Visualization
1
Start with n = 15
Our input number ready for decomposition
2
Find prime factors
15 = 3 × 5, so we get factors [3, 5]
3
Sum factors: 3 + 5 = 8
Replace n with the sum of its prime factors
4
Continue: 8 = 2³
8 breaks down to [2, 2, 2], sum = 6
5
Final step: 6 = 2 × 3
6 becomes [2, 3], sum = 5
6
Stop at prime
5 is prime, so we've reached our answer
Key Takeaway
🎯 Key Insight: The process always terminates because the sum of prime factors is always less than the original number (except for primes and special cases like 4).

Time & Space Complexity

Time Complexity
⏱️
O(n√n)

For each iteration, we check divisors up to √n, and we might have multiple iterations

n
2n
Linear Growth
Space Complexity
O(1)

Only using a few variables to store the current number and sum

n
2n
Linear Space

Constraints

  • 1 ≤ n ≤ 105
  • n is a positive integer
  • The process will always terminate in a finite number of steps
Asked in
Google 25 Amazon 20 Meta 15 Microsoft 12
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen