参考http://www.cnblogs.com/clive/archive/2009/10/28/Circular_decimal_fraction_USCAO_2_4_5.html
用分母中2的因子个数减去分子中2的因子个数,同样用分母中5的因子个数减去分子中5的因子个数,取这两者个数的最大值,
这个就是分数的非循环部分的长度,这样偏移后,后面就是循环部分,直到重复。
代码如下:
#include <iostream>
using namespace std;
int countBeforeRepeat(int n, int d)
{
int count5n = 0, count2n = 0;
while(d % 2 == 0)
{
d = d/2;
count2n++;
}
while(d % 5 == 0)
{
d = d/5;
count5n++;
}
while(n % 2 == 0)
{
n = n/2;
count2n--;
}
while(n % 2 == 0)
{
n = n/5;
count5n--;
}
if(count2n > count5n)
{
if(count2n > 0) return count2n;
else return 0;
}else
{
if(count5n > 0) return count5n;
else return 0;
}
}
int main()
{
int n, d;
cin >> n >> d;
cout << (n/d);
cout << ".";
n = n%d;
if(n == 0)
{
cout << 0 << endl;
return 0;
}
int count = countBeforeRepeat(n, d);
for(int i=0; i<count; i++)
{
n = n*10;
cout << (n/d);
n = n%d;
}
int r = n;
if(r != 0)
{
cout << "(";
do {
n = n*10;
cout << (n/d);
n = n%d;
} while(n != r);
cout << ")" << endl;
}
return 0;
}