求分数的循环节的长度

两个整数做除法,有时会产生循环小数,其循环部分称为:循环节

比如,11/13 = 0.846153846153...其循环节为846153共六位

思路:

模拟除法,只要寻找到相同余数,就找到了循环节

代码如下:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <iostream>
 4 #include <string>
 5 #include <math.h>
 6 #include <algorithm>
 7 #include <vector>
 8 #include <queue>
 9 #include <set>
10 #include <stack>
11 #include <map>
12 #include <sstream>
13 const int INF=0x3f3f3f3f;
14 typedef long long LL;
15 const int mod=1e9+7;
16 const int maxn=1e5+10;
17 using namespace std;
18 
19 vector<int> vt;
20 
21 int main()
22 {
23     int n,m;
24     scanf("%d %d",&n,&m);
25     int t=n;
26     int ans=0;
27     t=t%m;
28     while(1)
29     {
30         vt.push_back(t);//将余数存下 
31         t*=10;
32         t=t%m;
33         if(t==0) break;    //可以除尽 
34         else if(find(vt.begin(),vt.end(),t)!=vt.end())//找到相同的余数,即找到了循环节 
35         {
36             ans=vt.end()-find(vt.begin(),vt.end(),t);//求循环节长度 
37             break;
38         }
39     }
40     printf("%d\n",ans);
41     return 0;
42 }

猜你喜欢

转载自www.cnblogs.com/jiamian/p/12099600.html