-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmallestPrimeFactorSum.c
More file actions
53 lines (49 loc) · 1005 Bytes
/
Copy pathsmallestPrimeFactorSum.c
File metadata and controls
53 lines (49 loc) · 1005 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* https://leetcode.com/problems/smallest-value-after-replacing-with-sum-of-prime-factors/
* Math, Number Theory
* Medium
*/
#include <stdio.h>
#include <stdbool.h>
bool is_prime(int x) {
if (x == 1) {
return false;
}
if (x == 2) {
return true;
}
for (int i = 2; i * i <= x; i++) {
if (x % i == 0) {
return false;
}
}
return true;
}
// Assume isn't prime
int sum_of_factors(int x) {
int total = 0;
int i = 2;
while (!is_prime(x) && i * i <= x) {
if (x % i == 0) {
total += i;
x /= i;
i = 2;
} else {
i++;
}
}
total += x;
return total;
}
int smallestValue(int n){
while (!is_prime(n) && n != sum_of_factors(n)) {
n = sum_of_factors(n);
}
return n;
}
int main() {
int n;
printf("Input n:\n");
scanf("%i", &n);
printf("Smallest Value After Replacing With Sum of Prime Factors: %i\n", smallestValue(n));
}