Mathematics:Dead Fraction(POJ 1930)

              

                消失了的分式

  题目大意:某个人在赶论文,需要把里面有些写成小数的数字化为分式,这些小数是无限循环小数(有理数),要你找对应的分母最小的那个分式(也就是从哪里开始循环并不知道)。

  一开始我也是蒙了,这尼玛什么鬼啊,后来百度了一下,原来这是小学的奥赛题?所有的无限循环小数都可以化为有理分式。

  公式:

  

  接下来就是找分母最小的那个,这个因为可以化简,所以直接用gcd就可以了

  果然涉及数学我就不太行惹,参考http://blog.csdn.net/xinghongduo/article/details/6231107

  

 1 #include <iostream>
 2 #include <functional>
 3 #include <algorithm>
 4 #include <math.h>
 5 
 6 using namespace std;
 7 
 8 int gcd(const int,const int);
 9 
10 static char str[1000];
11 
12 int main(void)
13 {
14     int sum, last, length, k, c, i, a, b, div, min_a, min_b;
15     while (~scanf("%s", str))
16     {
17         if (strlen(str) == 1 && str[0] == '0')
18             break;
19         sum = 0; length = 0; min_b = INT_MAX;
20         for (i = 2; str[i] != '.'; i++)
21         {
22             sum = sum * 10 + str[i] - '0';
23             length++;
24         }
25         c = (int)pow(10.0, length);
26         for (i = 1, last = sum, k = 1; i <= length; i++)
27         {
28             //不需要从0开始,没意义
29             last /= 10; k *= 10; c /= 10;
30 
31             a = sum - last;//取不循环部分
32             b = c*(k - 1);
33             
34             div = gcd(a, b);
35             if (b / div < min_b)
36             {
37                 min_a = a / div; 
38                 min_b = b / div;
39             }
40         }
41         printf("%d/%d\n", min_a, min_b);
42     }
43     return 0;
44 }
45 
46 int gcd(const int a, const int b)
47 {
48     if (b == 0)
49         return a;
50     return gcd(b, a%b);
51 }

posted @ 2015-11-20 23:56  PhiliAI  阅读(420)  评论(0编辑  收藏  举报