-
Notifications
You must be signed in to change notification settings - Fork 5
/
gcd.c
63 lines (51 loc) · 1.15 KB
/
gcd.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
typedef struct FACTOR
{
int *factors;
int count;
} Factor;
Factor get_common_factors(int a, int b)
{
int root = (int) sqrt(a);
int *factors = (int *) malloc((a / 2) * sizeof(int));
int j = 0;
for (int i = 1; i <= root; i++) {
if (a % i == 0) {
if (b % i == 0) {
factors[j++] = i;
}
int f = a / i;
if (f != i && b % f == 0) {
factors[j++] = a / i;
}
}
}
Factor factor = {
.factors = factors,
.count = j
};
return factor;
}
int gcd(int a, int b)
{
Factor common_factors = get_common_factors(a, b);
int largest = common_factors.factors[0];
for (int i = 1; i < common_factors.count; i++) {
if (common_factors.factors[i] > largest) {
largest = common_factors.factors[i];
}
}
return largest;
}
int main()
{
assert(6 == gcd(888, 78));
assert(5 == gcd(45, 25));
assert(2 == gcd(142, 872));
assert(111 == gcd(999, 111));
assert(250 == gcd(4500, 1250));
return 0;
}