Smallest Value After Replacing With Sum of Prime Factors Problem
#2507
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2507.
You are given a positive integer n.
Continuously replace n with the sum of its prime factors.
- Note that if a prime factor divides
nmultiple times, it should be included in the sum as many times as it dividesn.
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 <= 10^5
Solution
Approach: Simulation
Do exactly what the statement says: factorize n by trial division, add up its prime factors (with repetition), and replace n with that sum. Stop when the sum equals the current n, which happens when n is prime. The value strictly shrinks otherwise, so the loop ends quickly.
Complexity: O(sqrt(n)) per round, and only a few rounds are needed. O(1) space.
class Solution:
def smallestValue(self, n: int) -> int:
while 1:
t, s, i = n, 0, 2
while i <= n // i:
while n % i == 0:
n //= i
s += i
i += 1
if n > 1:
s += n
if s == t:
return t
n = s