算法竞赛入门经典(第2版) Repeating Decimals UVa 202

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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值