Problem 1029 - Decimal

/*

Time Limit: 1000MS   Memory Limit: 65536KB   Difficulty:
Total Submit:
87  Accepted: 15  Special Judge: No
Description
The rational number and
the irrational number makes the set of real number. As a mathematics fan,
Tiantian prefer investigating the kind of rational number with the form of 1/n.
That kind of rational number can be a finite decimal or a recurring decimal. For
example, 1/5 = 0.2 and 1/3 = 0.33333.... To learn the rational number more
clearly, Tiantian came to ask you to write a program for her. The program may be
able to return any number of the rational number with the form of
1/n.

Input
There are multiple test cases. Each case takes one line and
contains two integers s and n (1≤s≤5000, 1≤n≤2^31-1) separated by a single
space. It describes that Tiantian would like to know the nth number after the
decimal point of 1/s.
s=0,n=0 indicates the end of the input and should not
be processed by your program.
Output
For each case, output one line with
the nth number after the decimal point of the rational number 1/s.
Sample
Input
2 2
5 1
13 6
0 0
Sample Output
0
2
3

*/

如果直接枚举肯定超时,题目就是求1/s的小数点后第n位,如果1/s是有限小数直接求,如果是无限循环小数,可以通过记录当前的被除数,当被除数重复时就是循环节出现的时候,循环节出现。这题我是RE但是能力有限,真的是没查出来哪里数组越界或者哪里除0了,没用指针肯定不是指针的问题,所以,我学习了别人的代码,供大家一起学习。这个我注释写的比较清楚,不废话,上AC代码

 1 #include<stdio.h>
 2 int a[5010],flag[5010],n,s;
 3 int cal()
 4 {
 5     int i;
 6     int len=0,p=1%s;       //p为余数
 7     for (i=0; i<s; i++) flag[i]=0;  //初始化
 8     do
 9     {
10         flag[p]=++len;  //flag记录位数
11         a[len]=p*10/s;  //a记录商
12         p=p*10%s;   //p为余数
13     }
14     while (p>0 && !flag[p]);   //余数不为0或p未被标记时继续
15     if (p==0) //余数为0导致退出时
16              if (n<=len) return a[n];  //如果输入n小于等于此时余数为0的长度,返回a[n]
17              else return 0;  //大于余数为0的长度,余数肯定为0
18     if (n<=flag[p]-1) return a[n];  //由于p已被记录过导致循环结束时,如果n还没到循环开始的位置flag[p],返回a[n]
19     else if ((n-flag[p]+1)%(len+1-flag[p])==0) return a[len];    //还是循环后如果余数为0,返回a[len]
20     else return a[(n-flag[p]+1)%(len+1-flag[p])+flag[p]-1];    //不为0就按循环节及开始点去计算
21 }
22 int main()
23 {
24     while (scanf("%d%d",&s,&n)!=EOF&&(s+n)!=0)
25         printf("%d\n",cal());
26     return 0;
27 }

 

posted @ 2013-08-10 21:42  hjf007  阅读(212)  评论(0编辑  收藏  举报