Problem Description
Given a positive integer n, repeatedly replace n with the sum of its prime factors (each occurrence of a prime factor is counted as many times as it divides n). Return the smallest value that n takes on through this process.
Key Insights
- The core task is to perform prime factorization for the current value of n.
- Each prime factor appears in the sum as many times as its multiplicity in n.
- The process is repeated until the sum of the prime factors equals n, meaning a fixed point is reached.
- Efficient prime factorization using trial division (up to sqrt(n)) is crucial given the constraint (n up to 10^5).
Space and Time Complexity
Time Complexity: Each factorization uses trial division up to sqrt(n), which is O(sqrt(n)). Even though multiple iterations might occur, n typically reduces quickly. Space Complexity: O(1) extra space is used, aside from a few integer variables.
Solution
The solution simulates the process iteratively. For each current n:
- Factorize n using trial division.
- Sum the factors, counting each factor as many times as it divides n.
- Compare the sum with n. If they are equal, the smallest value has been found; otherwise, update n with this sum and continue. The only data structure used is plain integers for storing values such as the current sum, temporary variable for factorization, and the factor itself. The algorithm leverages trial division to extract prime factors efficiently.