Skip to content

Latest commit

 

History

History

2507

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

You are given a positive integer n.

Continuously replace n with the sum of its prime factors.

  • Note that 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.

 

Example 1:

Input: n = 15
Output: 5
Explanation: Initially, n = 15.
15 = 3 * 5, so replace n with 3 + 5 = 8.
8 = 2 * 2 * 2, so replace n with 2 + 2 + 2 = 6.
6 = 2 * 3, so replace n with 2 + 3 = 5.
5 is the smallest value n will take on.

Example 2:

Input: n = 3
Output: 3
Explanation: Initially, n = 3.
3 is the smallest value n will take on.

 

Constraints:

  • 2 <= n <= 105

Related Topics:
Math, Number Theory

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/smallest-value-after-replacing-with-sum-of-prime-factors
// Author: github.com/lzl124631x
// Time: O(Sqrt(N))
// Space: O(Sqrt(N))
class Solution {
    vector<int> factors(int n) {
        vector<int> ans;
        for (int i = 2; i * i <= n; ++i) {
            while (n % i == 0) {
                n /= i;
                ans.push_back(i);
            }
        }
        if (n > 1) ans.push_back(n);
        return ans;
    }
public:
    int smallestValue(int n) {
        while (true) {
            auto fs = factors(n);
            int m = accumulate(begin(fs), end(fs), 0);
            if (m == n) return n;
            n = m;
        }
    }
};