数论GCD·无限循环小数转分数

根据如上定理,我们便可以解决这道题了:

AC代码:

#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <bitset>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include <cstring>
#include <iostream>
#include <algorithm>
#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;
#define   maxn          1010
#define   lson          l,m,rt<<1
#define   rson          m+1,r,rt<<1|1
#define   ms(x,y)      memset(x,y,sizeof(x))
#define   rep(i,n)      for(int i=0;i<(n);i++)
#define   repf(i,a,b)   for(int i=(a);i<=(b);i++)
#define   PI           pair<int,int>
//#define   mp            make_pair
#define   FI            first
#define   SE            second
#define   IT            iterator
#define   PB            push_back
#define   Times         10
typedef   long long     ll;
typedef   unsigned long long ull;
typedef   long double   ld;
typedef   pair<int ,int > P;
//#define N 100
const double eps = 1e-10;
const double  pi = acos(-1.0);
const  ll    mod = 1e9+7;
const  int   inf = 0x3f3f3f3f;
const  ll    INF = (ll)1e18+300;
const int   maxd = 51000 + 10;

bool judge_zero(string s) {
    for (int i = 2; i < s.length(); i++) {
        if(s[i] != '0') {
            return false;
        }
    }
    return true;
}

int gcd(int a,int b) {
    if(!b) {
        return a;
    }
    else return gcd(b, a%b);
}
int main() {
    string s;
    while(cin >> s) {
        if(s.length() == 1 && s[0] == '0') {
            break;
        }
        if(judge_zero(s)) {
            cout << "0/1\n" << endl;
            continue;
        }
        int len = s.length();
        ll res = 0;
        int num = 0;
        for (int i = 2; i < len; i++) {
            if(s[i] == '.') {
                break;
            }
            num ++ ;
            res = res * 10 + s[i] - '0';
        }
        int min_fz = inf, min_fm = inf;
        //cout << res << endl;
        for (int cnt = res, k = 1, i = 1; i <= num; i ++) {
            cnt /= 10;
            int a = res - cnt;
            k *= 10;
            int l = num - i;
            int cns = res - cnt;
            int ans = (int)pow(10.0, l) * (pow(10.0, i) - 1);
            int com = gcd(cns, ans);
            if(ans / com < min_fm) {
                min_fz = cns / com;
                min_fm = ans / com;
            }
        }
        cout << min_fz << "/" << min_fm << endl;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值