Smallest Value After Replacing With Sum of Prime Factors - Problem

You are given a positive integer n.

Continuously replace n with the sum of its prime factors.

Note: If a prime factor divides n multiple times, it should be included in the sum as many times as it divides n.

Return the smallest value n will take on.

Input & Output

Example 1 — Basic 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, return 5.
Example 2 — Already Prime
$ Input: n = 3
Output: 3
💡 Note: 3 is already prime, so it cannot be reduced further. Return 3.
Example 3 — Power of Prime
$ Input: n = 8
Output: 5
💡 Note: 8 = 2³, sum = 2+2+2 = 6. Then 6 = 2×3, sum = 2+3 = 5. Since 5 is prime, return 5.

Constraints

  • 2 ≤ n ≤ 1000

Visualization

Tap to expand
Smallest Value After Sum of Prime Factors INPUT n = 15 Positive Integer Prime Factorization: 15 = 3 x 5 Two prime factors Iteration Process: n=15 --> 3+5 = 8 n=8 --> 2+2+2 = 6 n=6 --> 2+3 = 5 n=5 --> 5 (prime!) OK ALGORITHM STEPS 1 Check if Prime If n is prime, return n (Early termination) 2 Find Prime Factors Factorize n completely Include repeated factors 3 Sum All Factors Replace n with sum e.g., 15 --> 3+5 = 8 4 Repeat Until Prime Loop back to step 1 Stop when n is prime Optimization: isPrime(n) check first Avoids unnecessary work FINAL RESULT 5 Smallest Value Execution Trace: 15 --> 3+5=8 8 --> 2+2+2=6 6 --> 2+3=5 5 --> PRIME! Total iterations: 3 Output: 5 Verified Correct Key Insight: The sum of prime factors is always less than n (for composite n), so the sequence decreases. Early prime check optimization: Before factorizing, check if n is already prime to avoid unnecessary computation. The smallest possible result is always a prime number (often 2, 3, or 5 for small inputs). TutorialsPoint - Smallest Value After Replacing With Sum of Prime Factors | Optimized with Early Prime Check
Asked in
Google 15 Microsoft 12
12.0K Views
Medium Frequency
~15 min Avg. Time
450 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