Examples of decimal expansions of rational numbers and their repeating cycles are shown below. Here, we use parentheses to enclose the repeating cycle rather than place a bar over the cycle.
fraction decimal expansion repeating cycle cycle length 1/6 0.1(6) 6 1 5/7 0.(714285) 714285 6 1/250 0.004(0) 0 1 300/31 9.(677419354838709) 677419354838709 15 655/990 0.6(61) 61 2
Write a program that reads numerators and denominators of fractions and determines their repeating cycles.
For the purposes of this problem, define a repeating cycle of a fraction to be the first minimal length string of digits to the right of the decimal that repeats indefinitely with no intervening digits. Thus for example, the repeating cycle of the fraction 1/250 is 0, which begins at position 4 (as opposed to 0 which begins at positions 1 or 2 and as opposed to 00 which begins at positions 1 or 4).
Input
Each line of the input file consists of an integer numerator, which is nonnegative, followed by an integer denominator, which is positive. None of the input integers exceeds 3000. End-of-file indicates the end of input.
Output
For each line of input, print the fraction, its decimal expansion through the first occurrence of the cycle to the right of the decimal or 50 decimal places (whichever comes first), and the length of the entire repeating cycle. In writing the decimal expansion, enclose the repeating cycle in parentheses when possible. If the entire repeating cycle does not occur within the first 50 places, place a left parenthesis where the cycle begins — it will begin within the first 50 places — and place ‘...)’ after the 50th digit.
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
题解:这是一道于循环有关的题,用数组分别记下小数位上每一位的数以及这个小数位上的数除以分母所得的值(小数),因为这个值也是多位的小数,所以如果这个小数与之前某一位上的小数想等,就证明进入了循环节,接下来就没有必要继续进行下去了;没错这又是一道水题,但是有几点需要注意的,首先要知道如何分别计算每一位小数位上的数,这个是基础,用字符串就行,不过就是乘十取余而已,然后注意循环的变量不要保存为局部变量,这样可以方便一点;
code:
#include <iostream>
#include <cstdio>
#define maxn 3000+50
using namespace std;
int main()
{
double mod[maxn];//存每一位的小数;
int ans[maxn];//存每一位的数;
int a,b;
int len;//循环节的长度;
bool flag;
while(cin>>a>>b)
{
ans[0]=a/b;//整数部分;
mod[0]=a;
flag=0;
int i,j;
for(i=1; ; i++)
{
mod[i]=(mod[i-1]-ans[i-1]*b)*10;
ans[i]=mod[i]/b;
for(j=1; j<i; j++)
{
if(mod[i]==mod[j])
{
len=i-j;
flag=1;
break;
}
}
if(flag==1)
break;
}
//print;
printf("%d/%d = %d.",a,b,ans[0]);
for(int i=1; i<j; i++)
{
printf("%d",ans[i]);
}
cout<<'(';
if(len>50)
{
for(int k=j; k<=50; k++)
{
printf("%d",ans[k]);
}
printf("...)\n ");
}
else
{
for(int k=j; k<i; k++)
{
printf("%d",ans[k]);
}
printf(")\n ");
}
printf("%d = number of digits in repeating cycle\n\n",len);
}
return 0;
}