Rational Ratio (2018 ACM-ICPC North Central North America Regional Contest)

本文介绍了一种将带有无限循环部分的十进制小数转换为其最简分数形式的算法。通过输入小数点后的循环位数,算法能够找到表示相同数值的两个整数的比,且该比为最简形式。

滴答滴答---题目链接 

Every (positive) rational number can be expressed as a ratio of two (positive) integers. However, in decimal form, rational numbers often have an infinitely repeating pattern, e.g., 1/7=0.1428571428571428571/7=0.142857142857142857... A convenient way of writing this repeating pattern is to put a bar over the first occurrence of the repeating part, so 1/71/7 would be written:

0.142857⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯.0.142857¯.

Given a rational number consisting of a series of digits, followed by a decimal point, followed by more digits, and then a number indicating how many of the rightmost digits repeat (i.e., the number of digits under the bar), your task is to find the ratio of two integers, in the most reduced form, that represent the same rational number. For example, for the input “0.1428570.142857 66” you should find 1/71/7.

Input

The input will be a single line with two numbers separated by one space. The first number will consist of 11 to 33 digits (00–99), followed by a decimal point, followed by 11 to 1111 digits (00–99), representing the decimal form of the number, possibly with leading zeros. The second number will be a positive integer indicating how many of the rightmost digits of the preceding number repeat. The first number will always be greater than 00. The second number will never be less than 11 nor larger than the number of digits to the right of the decimal point.

Output

Print the corresponding fraction in its most reduced form, that is, the fraction with the smallest possible integer values in the numerator and denominator.

Sample Input 1Sample Output 1
0.142857 6
1/7
Sample Input 2Sample Output 2
1.6 1
5/3
Sample Input 3Sample Output 3
123.456 2
61111/495

      题意:把给出的循环小数,转换为分数

     

//#include <iostream>
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
    char ch;
    string s;
    ll fm=1,fz=0,tt;
    int k;
    cin>>tt>>ch>>s>>k;
    int len=s.size();
    for(int i=len-k; i<len; i++)
    {
        fz=fz*10+s[i]-'0';
    }
    for(int i=0; i<k; i++)
        fm*=10;
    fm--;
    ll tf=1;
    for(int i=0; i<len-k; i++)
    {
        fm*=10;
        tf*=10;
        tt=tt*10+s[i]-'0';
    }
    ll ffm=tf*fm;
    ll ffz=tt*fm+fz*tf;
    ll ans=__gcd(ffz,ffm);
    ffz/=ans;
    ffm/=ans;
    cout<<ffz<<"/"<<ffm<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值