Input: n =15Output: 5Explanation: Initially, n =15.15=3*5, so replace n with3+5=8.8=2*2*2, so replace n with2+2+2=6.6=2*3, so replace n with2+3=5.5is the smallest value n will take on.
At each step, replace n with the sum of its prime factors (counting multiplicity). If n is already prime, it will not change. The process always converges to a prime, which is the smallest value n will take on.
classSolution {
public:int smallestValue(int n) {
while (true) {
int x = n, s =0, d =2;
while (x >1) {
while (x % d ==0) { s += d; x /= d; }
d++;
if (d * d > x) d = x;
}
if (s == n) break;
n = s;
}
return n;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
funcsmallestValue(nint) int {
for {
x, s, d:=n, 0, 2forx > 1 {
forx%d==0 { s+=d; x/=d }
d++ifd*d > x { d = x }
}
ifs==n { break }
n = s }
returnn}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintsmallestValue(int n) {
while (true) {
int x = n, s = 0, d = 2;
while (x > 1) {
while (x % d == 0) { s += d; x /= d; }
d++;
if (d * d > x) d = x;
}
if (s == n) break;
n = s;
}
return n;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funsmallestValue(n0: Int): Int {
var n = n0
while (true) {
var x = n; var s = 0; var d = 2while (x > 1) {
while (x % d ==0) { s += d; x /= d }
d++if (d * d > x) d = x
}
if (s == n) break n = s
}
return n
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defsmallestValue(self, n: int) -> int:
whileTrue:
x, s, d = n, 0, 2while x >1:
while x % d ==0:
s += d
x //= d
d +=1if d * d > x:
d = x
if s == n:
break n = s
return n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnsmallest_value(mut n: i32) -> i32 {
loop {
let (mut x, mut s, mut d) = (n, 0, 2);
while x >1 {
while x % d ==0 { s += d; x /= d; }
d +=1;
if d * d > x { d = x; }
}
if s == n { break; }
n = s;
}
n
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
smallestValue(n: number):number {
while (true) {
letx=n, s=0, d=2;
while (x>1) {
while (x%d===0) { s+=d; x/=d; }
d++;
if (d*d>x) d=x;
}
if (s===n) break;
n=s;
}
returnn;
}
}