Repeating Decimals UVa 202
—————————————————————————
题目:UVa202
—————————————————————————
思路:a/b得到小数点左边的数字,将这个数字先存入answer数组,计算m+1次时至少存在一个余数相同,即为循环节。
PS:抽屉原理的应用
Sample Input
76 25
5 43
1 397
Sample Output
76/25 = 3.04(0)
1 = number of digits in repeating cycle
5/43 = 0.(116279069767441860465)
21 = number of digits in repeating cycle
1/397 = 0.(00251889168765743073047858942065491183879093198992...)
99 = number of digits in repeating cycle
#include<bits/stdc++.h>
using namespace std;
int main(){
int a, b;
int remainder[30005], answer[30005], mark[30005];
while(scanf("%d%d", &a, &b) != EOF) { //没有!=EOF会造成Time limit Exceeded
int cnt = 0;
memset(answer, 0, sizeof(answer));
memset(mark, 0, sizeof(answer));
answer[cnt++] = a/b;
printf("%d/%d = %d.", a, b, answer[0]);
a = a % b;
while(a && mark[a] == 0) {
mark[a] = cnt;
remainder[cnt] = a;
answer[cnt++] = a*10/b;
a = 10*a%b;
}
for(int i = 1; i < cnt && i <= 50; i++) {
if(a && remainder[i] == a) {
printf("(");
}
printf("%d", answer[i]);
}
if(!a) printf("(0");
if(cnt > 50) printf("...");
printf(")\n");
int res = cnt - mark[a];
if(a == 0) res = 1;
printf(" %d = number of digits in repeating cycle\n\n", res);
}
return 0;
}