HDU1717 (循环小数化分数)

51 篇文章 0 订阅

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1717


分析:

我们将这个循环小数分成三部分0.a1a2a3a4....an(b1b2bb3...bm) 分成0,不循环的部分a1a2...an,和循环节b1b2b3...bm

设这个小数为X,a1a2a3....an=s1, b1b2b3...bm=s2,y=0.(b1b2b3b4..bm)

X * 10^n = s1 + y;       ---------1)

y * 10^m = s2 + y;      ----------2)

由2)得  y = s2 / ( 10^m - 1 );   ------------3)

1) ,3)联立

x=( s2 + s1 *( 10^m - 1) ) / ( 10^n * ( 10^m -1 ) );

在处理的时候要注意m=0,或者n=0,的情况


代码如下:

#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;

typedef long long LL;

LL gcd(LL a,LL b)
{
    if(b) return gcd(b,a%b);
    return a;
}

char a[10000];

int main()
{
    int n;
    scanf("%d",&n);
    while(n--){
        scanf("%s",a);
        LL z1 = 0,cnt=0,m=0,cnt2=0,ff=100000,z2=0;
        for(int i=1;i<strlen(a);i++){
            if(a[i]!='.'&&a[i]!='('&&i<ff){
                z1=z1*10+a[i]-'0';
                if(i<ff)
                    cnt++;
            }
            if(a[i]=='(') ff=i;
            if(i>ff&&a[i]!=')') z2=z2*10+a[i]-'0',cnt2++;
        }
        LL tmp1=1,tmp2=1,tmp,z;
        for(int i=0;i<cnt;i++)
            tmp1*=10;
        for(int i=0;i<cnt2;i++)
            tmp2*=10;
        if(tmp1==1){
            z=z2;
            m=tmp2-1;
            tmp=gcd(z,m);
            printf("%I64d/%I64d\n",z/tmp,m/tmp);
            continue;
        }
        if(tmp2==1){
            z=z1,m=tmp1;
            tmp=gcd(z,m);
            printf("%I64d/%I64d\n",z/tmp,m/tmp);
            continue;
        }
        z=z2+(tmp2-1)*z1;
        m=tmp1*(tmp2-1);
        tmp=gcd(z,m);
        printf("%I64d/%I64d\n",z/tmp,m/tmp);
    }
    return 0;
}

   


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值