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 }

 

转载于:https://www.cnblogs.com/hjf007/p/3250740.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值