-
Notifications
You must be signed in to change notification settings - Fork 5
/
common_factors.c
61 lines (50 loc) · 1.23 KB
/
common_factors.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
#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 main()
{
int test_data[3][2] = {
{54, 27},
{350, 105},
{81, 405}
};
Factor factors;
for (int i = 0; i < 3; i++) {
factors = get_common_factors(test_data[i][0], test_data[i][1]);
printf("\n%d common factors for (%d, %d): ", factors.count, test_data[i][0], test_data[i][1]);
for (int k = 0; k < factors.count; k++) {
printf("%d ", factors.factors[k]);
assert(test_data[i][0] % factors.factors[k] == 0);
assert(test_data[i][1] % factors.factors[k] == 0);
}
}
return 0;
}