from fractions import Fraction
n = 103
d = 104
nd = Fraction(n, d)
d1 = 1
while nd != 0:
d1 = d1 + 1
if Fraction(1, d1) <= nd:
testfrac = Fraction(1, d1)
nd = nd - testfrac
print(testfrac)
试图计算埃及分数。它适用于更平滑的计算,但当while循环必须不断测试更高的数字时,它的效率不够。while循环将继续运行,但最终会停止,并且不会测试此计算的最后两部分。是否存在d1将访问的最大号码
在进入连续增量之前,应尝试根据分母/分子的比率将剩余分数转换为1/n。这使总和更快地收敛到目标分数。您还将发现,当比率不完美时,只需在分母上加1:
输出:
基于此,可以将其实现为一个递归生成器,只返回要相加的埃及分数的分母(并且运行得更快):
输出:
最短形式
如果您正在寻找分母最小的最短形式(最少的术语数),则需要递归方法。这是一个递归生成器,它生成最短形式的变量,我们可以从中选择分母和最小的变量:
输出:
您应该查看其他算法,以了解人们如何在合理的时间内解决这些问题。我发现rosettacode.org上的Python实现速度非常快。下面是一个基于one over there的最小版本:
计算时间几乎是任何分数的眨眼时间
相关问题 更多 >
编程相关推荐