無限循環小數化分數

Problem I: Dead Fraction

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 54  Solved: 8
[Submit][Status][Web Board]

Description

Mike is frantically scrambling to finish his thesis at the last minute. He needs to assemble all his research notes into vaguely coherent form in the next 3 days. Unfortunately, he notices that he had been extremely sloppy in his calculations. Whenever he needed to perform arithmetic, he just plugged it into a calculator and scribbled down as much of the answer as he felt was relevant. Whenever a repeating fraction was displayed, Mike simply reccorded the first few digits followed by "...". For instance, instead of "1/3" he might have written down "0.3333...". Unfortunately, his results require exact fractions! He doesn't have time to redo every calculation, so he needs you to write a program (and FAST!) to automatically deduce the original fractions.

To make this tenable, he assumes that the original fraction is always the simplest one that produces the given sequence of digits; by simplest, he means the the one with smallest denominator. Also, he assumes that he did not neglect to write down important digits; no digit from the repeating portion of the decimal expansion was left unrecorded (even if this repeating portion was all zeroes).

There are several test cases. For each test case there is one line of input of the form "0.dddd..." where dddd is a string of 1 to 9 digits, not all zero. A line containing 0 follows the last case. For each case, output the original fraction.

Note that an exact decimal fraction has two repeating expansions (e.g. 1/5 = 0.2000... = 0.19999...).

Input

Output

Sample Input

0.2...
0.20...
0.474612399...
0

Sample Output

2/9
1/5
1186531/2500000


題意:很有意思的一道題,,將一個無限循環小數轉化成分母最小的精確分數值....
(注意:循環的部分不一定是最後一位,有可能從小數點後面全是循環部分...我因爲這個問題WA了2次,題意模糊)
思路:先推導一個數學等式...過程如下(windows畫圖寫的,很不美觀>_<):
<img src="https://img-blog.csdn.net/20160520223803864?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
推導出上述等式,就可以在知道循環部分和非循環後計算出其精確分數值...所以只需要枚舉這個數的末端,將其作爲循環部分,其餘爲非循環
部分即可計算出分母最小的精確分數值....
代碼如下:<pre class="cpp" name="code">#include<iostream>
#include<math.h>
using namespace std;
int gcd(int a,int b)
{
if(!a)
return b;
return gcd(b%a,a);
}
int main()
{
char str[100];//儲存小數的字符數組
int num,k,all,a,b,i,j,mina,minb,l;
while(cin>>str&&strcmp(str,"0"))
{
mina=minb=1000000000;
for(i=2,all=0,l=0;str[i]!='.';i++)//從小數部分開始,故i=2開始,直到遇到'.'
{
all=all*10+str[i]-48;
l++;
}
for(num=all,k=1,i=1;i<=l;i++)
{
num/=10;
k*=10;
a=all-num;
b=(int)pow(10.0,l-i)*(k-1);
j=gcd(a,b);
if(b/j<minb)
{
mina=a/j; 
minb=b/j;
}
}
cout<<mina<<'/'<<minb<<endl;
}
return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章