-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem33.c
94 lines (83 loc) · 1.61 KB
/
problem33.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* Copyright (c) 2009, eagletmt
* Released under the MIT License <http://opensource.org/licenses/mit-license.php>
*/
#include <stdio.h>
#include <math.h>
static unsigned gcd(unsigned a, unsigned b);
static int cancel(unsigned n1, unsigned d1, unsigned *n2, unsigned *d2);
int main(void)
{
unsigned ans_n = 1, ans_d = 1;
unsigned i;
for (i = 11; i < 100; i++) {
unsigned j;
if (i % 10 == 0) {
continue;
}
for (j = 11; j < i; j++) {
unsigned g, n, d;
unsigned n2, d2;
if (j % 10 == 0) {
continue;
}
if ((g = gcd(i, j)) == 1) {
continue;
}
/* cancel numerically */
n = j/g;
d = i/g;
/* cancel symbolically */
if (cancel(j, i, &n2, &d2)) {
unsigned g2 = gcd(n2, d2);
n2 /= g2; d2 /= g2;
if (n == n2 && d == d2) {
ans_n *= n;
ans_d *= d;
}
}
}
}
printf("%u\n", ans_d / gcd(ans_n, ans_d));
return 0;
}
unsigned gcd(unsigned a, unsigned b)
{
unsigned r;
while ((r = a % b) != 0) {
a = b; b = r;
}
return b;
}
int cancel(unsigned n1, unsigned d1, unsigned *n2, unsigned *d2)
{
if (n1%10 == d1%10) {
/* e.g. 24 and 34 */
*n2 = n1/10;
*d2 = d1/10;
return 1;
}
else if (n1%10 == d1/10) {
/* e.g. 24 and 41 */
*n2 = n1/10;
*d2 = d1%10;
return 1;
}
else if (n1/10 == d1%10) {
/* e.g. 24 and 32 */
*n2 = n1%10;
*d2 = d1/10;
return 1;
}
else if (n1/10 == d1/10) {
/* e.g. 24 and 21 */
*n2 = n1%10;
*d2 = d1%10;
return 1;
}
else {
*n2 = n1;
*d2 = d1;
return 0;
}
}