现在的位置: 首页 > 综合 > 正文

HDU 1717 数学题

2012年07月30日 ⁄ 综合 ⁄ 共 1200字 ⁄ 字号 评论关闭

题目地址:  http://acm.hdu.edu.cn/showproblem.php?pid=1717

首先跟你一个小数 令X= 0 . s1 s2 ..sn ( y1 y2 y3..ym ) 这样的话我们把小数点分为三个部分,分别用三种颜色标记了!

我们可以把表达式转换成:X * 10 ^n=s1s2..sn+0.y1y2..ym;    我们用S1替换 s1s2..sn ,Y替换 0.(y1y2..yn), 然后可以把表达式写成: X * 10^n=S1 + Y;  然后 Y=0.(y1y2..ym) 变形一下:Y * 10 ^m=y1y2..ym + Y; 在这里我们另y1y2..ym等于S2;

宗上所述:我们得到两个表达式 X * 10^n=S1 +  Y;    Y * 10^m=S2 + Y; 然后将两个式子合并成一个用表达式,

$$\frac{s2 + (10^m-1)*s1}{10^n * ( 10^m -1 )}$$然后就可以根据这个公式,求出分子分母的
最大公约式 然后化简 就可以了

注意讨论下不是无限循环小数的情况

代码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <deque>
#include <queue>
#include <iterator>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <cctype>
using namespace std;

typedef long long LL;
const int N=21;
const LL II=1000000007;

char s[N];

int gcd(int n,int m)
{
    while(m)
    {
        int t=n%m;
        n=m;
        m=t;
    }
    return n;
}

int main()
{
	int i,j,k,l,t;
	cin>>t;
    while(t--)
    {
        scanf("%s",s);
        int len=strlen(s);
        int s1=0,s2=0,i=2,j=0;
        int n=0,m=0;
        while(s[i]!='('&&i<len)
        {
            s1=s1*10+s[i]-'0';
            n++;
            i++;
        }
        j=i+1;
        while(s[j]!=')'&&j<len)
        {
            s2=s2*10+s[j]-'0';
            m++;
            j++;
        }
        int fenzi=(int)(s2+(pow(10.0,m)-1)*s1);
        int fenmu=(int)(pow(10.0,n)*(pow(10.0,m)-1));
        if(m==0)
        {//这个地方注意不是无限循环的小数
            fenzi=s1;
            fenmu=(int)pow(10.0,n);
        }
        int temp=gcd(fenzi,fenmu);
        printf("%d/%d\n",fenzi/temp,fenmu/temp);
    }
	return 0;
}

抱歉!评论已关闭.