-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp3.c
44 lines (34 loc) · 911 Bytes
/
p3.c
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
#include <stdio.h>
#include <math.h>
#define NUM 600851475143
#define ull unsigned long long
ull max_factor(ull);
int isprime(ull);
/* Problem:
find the biggest factor for a given number */
int main(void) {
printf("%llu", max_factor(NUM));
return 0;
}
ull max_factor(ull x) {
// returns the biggest factor of x
ull i = 2;
while(!isprime(i) || (x % i)) {
i++;
}
// after the loop, i divides x.
// so, x / i is the factorization of x without i.
// if x / i is a prime number, then its the biggest factor of x.
if(isprime(x / i)) return x / i;
// else, we need to re-run our algorithm on x / i.
return max_factor(x / i);
}
int isprime(ull x) {
// returns true if x is a prime number
// using naive O(sqrt x) algorithm
ull limit = (ull)sqrt(x), i;
for(i = 2; i < limit + 1; i++) {
if(!(x % i)) return 0;
}
return 1;
}