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

本文介绍了一种将任意真分数分解为一系列埃及分数的方法,并提供了一个使用C++实现的具体示例。通过逐步减小真分数的值,最终将其表示为若干个单位分数之和。

分子为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;
        }
    }
}


### 将真分数换为埃及分数之和的算法 为了将一个真分数 \( \frac{a}{b} \) 换为最少数量的埃及分数之和,可以使用斐波那契提出的贪心算法。该算法通过一系列迭代操作逐步减少原分数直至其变为零。 #### 算法描述: 给定两个互质正整数 \( a, b (a < b) \)分数 \( \frac{a}{b} \) 可按照如下方式分解成多个单位分数之和[^1]: - **初始化**:令当前待处理的分数为 \( \frac{a_0}{b_0} = \frac{a}{b} \)。 - 对于每一步骤: - 找到满足条件的最大整数值 \( c_i \geq q_i + 1 \),使得 \( \frac{1}{c_i} \leq \frac{a_{i}}{b_{i}} \); - 更新剩余未处理的部分为 \( \frac{a_{i+1}}{b_{i+1}} = \frac{a_i * c_i - b_i}{b_i * c_i} \); - 当 \( a_{i+1} = 1 \) 或者 \( a_{i+1} | b_{i+1} \)(即\( a_{i+1}\) 整除 \( b_{i+1} \))时停止循环并记录最终项\[ \frac{1}{\left(\frac{b_{i+1}}{a_{i+1}}\right)} \]。 下面是一个具体的例子展示此过程的应用: 假设需要计算的是 \( \frac{7}{8} \): 1. 初始状态: \( \frac{7}{8}, q_1=\lfloor{\frac{8}{7}}\rfloor=1,r_1=(8-(7*1))=1,\frac{7}{8}=1/\lceil{(1+1)\rceil}+\frac{(7-1)}{(8*(1+1))}=\frac{1}{2}+\frac{3}{8} \) 2. 接下来继续对剩下的部分 \( \frac{3}{8} \) 进行相同的操作... 最后得出的结果将是 \( \frac{7}{8} = \frac{1}{2} + \frac{1}{3} + \frac{1}{24} \). 下面是实现上述逻辑的一个简单 Python 函数示例: ```python def egyptian_fraction(a, b): result = [] while a != 0: # Find the ceiling of denominator / numerator to get next unit fraction's denominator. x = int(b / a) # Add this value as part of our solution set. result.append(x + 1) # Update 'a' and 'b'. a = a * (x + 1) - b b *= (x + 1) # If we have reached an exact match or can no longer divide further without remainder, # add last term directly from updated values of `a` & `b`. if a == 1 or b % a == 0: break if a > 0: result.append(int(b / a)) return ["1/" + str(i) for i in result] print(egyptian_fraction(7, 8)) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值