Dead Fraction POJ 1930(数学)

原题

题目链接

题目分析

无限循环小数化分数.把小数用分数表示,后面等比数列可以用求和公式化简,最后可以总结出一个通用公式(可以百度),这里不细讲.需要注意一下,题目没有明确说明循环部分从哪开始,因此需要枚举循环部分,找到分母最小的输出即可.

代码

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <utility>
 4 #include <cstdio>
 5 #include <cstdlib>
 6 #include <ctime>
 7 #include <cmath>
 8 #include <cstring>
 9 #include <string>
10 #include <vector>
11 #include <stack>
12 #include <queue>
13 #include <map>
14 #include <set>
15 
16 using namespace std;
17 typedef long long LL;
18 const int INF_INT=0x3f3f3f3f;
19 const LL INF_LL=0x3f3f3f3f3f3f3f3f;
20 
21 string s;
22 LL num[20];
23 
24 LL gcd(LL a,LL b)
25 {
26     return b?gcd(b,a%b):a;
27 }
28 
29 int main()
30 {
31 //    freopen("stdin.in","r",stdin);
32 //    freopen("stdout.out","w",stdout);
33     while(cin>>s)
34     {
35         if(s.size()==1) break;
36         int cnt=0;
37         for(int i=2;i<s.size();i++)
38             if(s[i]!='.') num[cnt++]=s[i]-'0';
39         LL ans,res,minn=INF_LL;
40         LL unrepeat,repeat,urpten,rpten,up,down;
41         for(int i=0;i<cnt;i++)
42         {
43             unrepeat=repeat=0;
44             urpten=rpten=1;
45             for(int j=i-1;j>=0;j--) unrepeat+=num[j]*urpten,urpten*=10;
46             for(int j=cnt-1;j>=i;j--) repeat+=num[j]*rpten,rpten*=10;
47 
48             up=unrepeat*rpten+repeat-unrepeat;
49             down=urpten*(rpten-1);
50 
51             LL g=gcd(up,down);
52             up/=g,down/=g;
53 
54             if(down<minn) ans=up,res=down,minn=down;
55         }
56         printf("%lld/%lld\n",ans,res);
57     }
58     return 0;
59 }

猜你喜欢

转载自www.cnblogs.com/VBEL/p/11438102.html