## 【UVA-202】Repeating Decimals【紫书】

【UVA-202】Repeating Decimals【紫书】

udebug数据链接：https://www.udebug.com/UVa/202

Solution:

```#include <iostream>
#include <map>
#include <string>

using namespace std;

map<int, int> pos;

void solve(string & ans, int & rest, int num, const int b) {
ans = ".";
pos.clear();

while (true) {
num *= 10;
int p = pos[num];

if (p == 0) {
pos[num] = ans.size();
} else {
rest = ans.size() - p;
if (rest > 50) {
ans.erase(p + 50);
ans += "...";
}
ans.insert(p, "(");
ans += ")";
break;
}

//do the cal
if (num < b) {
ans += "0";         //不够除的情况
} else {
int div = num / b, mod = num % b;
ans += (char)(div + '0');
if (!mod) {         //整除
ans += "(0)";
rest = 1;
break;
}
num = mod;          //迭代余数到被除数上
}
}
}

int main(void) {
int a, b;
while (scanf("%d%d", &a, &b) == 2) {
string ans = ".(0)";
int r = 1;
if (a % b)
solve(ans, r, a % b, b);
printf("%d/%d = %d%s\n", a, b, a / b, ans.c_str());
printf("   %d = number of digits in repeating cycle\n\n", r);
}
return 0;
}```