USACO Fractions to Decimals

Code

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
/*
ID: wcr19961
PROG: fracdec
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <set>
using namespace std;

set<int> s;
int main() {
freopen("fracdec.in", "r", stdin);
freopen("fracdec.out", "w", stdout);
int n, d;
scanf("%d%d", &n, &d);
int x = n / d;
printf("%d.", x);
n %= d;
if (n == 0) {
puts("0");
return 0;
}
int tmp = n, len = (x == 0 ? 0 : floor(log10(x))) + 2;
bool ok = false;
while (n) {
if (s.count(n)) {
ok = true;
break;
}
s.insert(n);
n *= 10;
n -= n / d * d;
}
swap(tmp, n);
if (tmp == 0) {
while (n) {
n *= 10;
printf("%d", n / d);
if (++len % 76 == 0) {
puts("");
}
n -= n / d * d;
}
} else {
int cnt = 0;
for (;;) {
if (n == tmp) {
if (cnt == 0) {
putchar('(');
} else {
putchar(')');
break;
}
if (++len % 76 == 0) {
puts("");
}
++cnt;
}
n *= 10;
printf("%d", n / d);
if (++len % 76 == 0) {
puts("");
}
n -= n / d * d;
}
}
if (len % 76) {
puts("");
}
return 0;
}