UVa 202 - Repeating Decimals
每次记录被除数 , 当出现相同被除数时即出现一个完整循环节
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1000;
char s[maxn];
char cyc[maxn];
int mo[100000];
int main()
{
int a,b;
while( ~scanf("%d%d",&a,&b) )
{
memset(s,0,sizeof(s));
memset(cyc,0,sizeof(cyc));
memset(mo,0,sizeof(mo));
if( a == b ){
printf("%d/%d = 1.(0)\n",a,b);
printf(" 1 = number of digits in repeating cycle\n\n");
continue;
}
else
{
int z = a / b;
/* 如果 a能整除b */
if( a % b == 0 ){
printf("%d/%d = %d.(0)\n",a,b,z);
printf(" 1 = number of digits in repeating cycle\n\n");
continue;
}
/* 如果 不整除 */
int cot = a % b; //每次的余数
cot *= 10;
mo[cot] = 1;
int i = 0;
int gg = 0; //记录突然整除
int f = 0;
while(1){
while( cot < b ){
cot *= 10;
s[i] = '0';
i++;
if(mo[cot]){ f = 1; break;}
mo[cot] = 1;
}
if(f) break;
if( cot % b == 0 ) //突然整除
{
s[i] = cot/b + '0';
printf("%d/%d = %d.%s(0)\n",a,b,z,s);
printf(" 1 = number of digits in repeating cycle\n\n");
gg = 1;
break;
}
s[i] = cot/b + '0';
i++;
//printf("%d %s\n",i,s);
cot %= b;
cot *= 10;
if( mo[cot] ) { break;}
//printf("%d is marked\n",cot);
mo[cot] = 1;
}
//printf("%s\n",s);
if(gg) continue;
int cott = a % b; //第二次循环寻找循环节开始的位置
cott *= 10;
int flag = 1;
int j = 0;
if( cot == cott ) flag = 0;
while(flag){
while( cott < b ){
cott *= 10;
j++;
}
if( cot == cott ) break;
cott -= cott/b * b;
cott *= 10;
if( cott > b && cott == cot ) { j++; break;}
if( cott > b ) j++;
}
if( i == j ){
char dd = s[i-1];
s[j-1] = '\0';
printf("%d/%d = %d.%s(%c)\n",a,b,z,s,dd);
printf(" 1 = number of digits in repeating cycle\n\n");
continue;
}
int k;
//printf("i = %d, j = %d %s\n",i,j,s);
int kk = 0;
int point = 0;
for( k = j; k < i; k++ ){
cyc[kk] = s[k];
kk++;
if(k == 49){
point = 1;
break;
}
}
cyc[kk] = '\0';
s[j] = '\0';
printf("%d/%d = %d.%s(%s",a,b,z,s,cyc);
if( point ) puts("...)");
else puts(")");
printf(" %d = number of digits in repeating cycle\n\n",i-j);
}
}
return 0;
}