真分数转埃及分数的和 (贪心)

77 篇文章 8 订阅
34 篇文章 3 订阅

分子为1的分数称为埃及分数。现输入一个真分数(分子比分母小的分数,叫做真分数),请将该分数分解为埃及分数。

例如6/7 = 1/2+1/3+1/42

题目分析:设原分数为a/b,b除a得到c,c+1作为第一个分母,拿a/b-1/c的值做第二个待分解的数直到a==1或者b%a==0

#include <cstdio>
#include <iostream>
#include <string>
using namespace std;

string toString(long long x) {
    string ans = "";
    while(x) {
        ans += x % 10 + '0';
        x /= 10;
    }
    int len = ans.length();
    for (int i = 0; i < len / 2; i ++) {
        swap(ans[i], ans[len - i - 1]);
    }
    return ans;
}

int main() {
    long long a, b;
    string ans = "";
    while(scanf("%lld/%lld", &a, &b) != EOF) {
        long c = 0;
        int cnt = 0;
        while (a != 1 && b % a) {
            cnt ++;
            if(cnt == 10)
                break;
            c = b / a + 1;
            a = a * c - b;
            b = b * c;
            ans += "1/";
            ans += toString(c);
            ans += "+";
        }
        if (a == 1) { 
            ans += "1/";
            ans += toString(b);
            cout << ans << endl;
        }
        else {
            ans += "1/";
            ans += toString(b / a);
            cout << ans << endl;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值