Problem Description
输入整数a 和 b(0<=a<=3000, 1 <= b <= 3000),输出a/b的循环小数表示以及循环节长度。例如a = 5, b = 43, 小数表示为0.(116279069767441860465),循环节长度为21。
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 s[3005], r[3005], vis[3005];//分别记录 第几个开始循环, 存储数据, 标记相应余数出现在第几位
int main()
{
int n, m;
while(~scanf("%d %d", &n, &m))
{
int cnt = 0;
memset(vis, 0, sizeof(vis));
r[cnt++] = n / m;//r[0]为整数部分
printf("%d/%d = ", n, m);
n = n % m;//余数
while(!vis[n] && n)//n不为0,n不重复
{
vis[n] = cnt;//记录当前的n是第几位循环数
s[cnt] = n;
n = n * 10;
r[cnt++] = n / m;
n = n % m;
}
printf("%d", r[0]);
printf(".");
int i;
for(i = 1; i <= 50 && i < cnt; i++)
{
if(s[i] == n && n) printf("(");//开始循环
printf("%d", r[i]);
}
if(!n) printf("(0");//循环节为0
if(cnt > 50) printf("...");//超过50位
printf(")\n");
printf(" %d = number of digits in repeating cycle\n\n", !n?1:cnt-vis[n]);//如果是0输出一位,vis记录了什么时候开始循环,cnt - vis[n]表示循环了多少位
}
}