# 2507. Smallest Value After Replacing With Sum of Prime Factors ###### tags: `Leetcode` `Medium` `Math` `Prime Factors` Link: https://leetcode.com/problems/smallest-value-after-replacing-with-sum-of-prime-factors/description/ ## 思路 如果我们能算出一个数n的所有prime factor的和s 然后令n=s 我们一直持续这个步骤 一直到n==s 就可以得到答案 那么重点就是如何计算一个数的所有prime factor ```java for(int i=2; i<=n; i++){ while(n%i==0){ n/=i; } } ``` 能进入到while回圈的每一个i都是prime factor ## Code ```java= class Solution { public int smallestValue(int n) { while(true){ int s = primes(n); if(n==s) break; n = s; } return n; } public int primes(int n) { int s = 0; for(int i=2; i<=n; i++){ while(n%i==0){ n/=i; s+=i; } } return s; } } ``` ```python= class Solution: def smallestValue(self, n: int) -> int: def primes(n: int) -> int: s = 0 for i in range(2, n+1): while n%i==0: n /= i s += i return s while n != (n:=primes(n)): pass return n ```