牛客华为机试HJ82
作者:互联网
1. 题目描述
2. Solution
1、思路
设要拆解的真分数为\(\frac{A}{B}\),设 B除以A的商为C,余数为D。即: \(B=A \cdot C+D\)。等式两边同时除以A,可得
\(\frac{B}{A} = C + \frac{D}{A} < C + 1(\because D < A)\) ,
易知C + 1是大于\(\frac{B}{A}\)的最小分数。将分式倒置有
\(\frac{A}{B} > \frac{1}{C+1}\)
即为真分数\(\frac{A}{B}\)包含的最大埃及分数。设\(E=C+1\),则有
\(\frac{A}{B} - \frac{1}{E} = \frac{AE-B}{BE}\)
继续上面的算法,直到A=1。
总结算法:
-
取\(g = gcd(A, B), A = A / g, B = B / g,除掉最大公约数\)
-
\(C = \left[ \frac{B}{A} \right] 向上取整, E = C + 1,导出 \frac{1}{E}\)
-
\(A =AE-B, B = BE,迭代计算,直到A=1\)
2、实现
最简单的实现自然是递归
import sys
if sys.platform != "linux":
file_in = open("input/HJ82.txt")
sys.stdin = file_in
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
def solve(A, B):
if A == 1:
print(f"1/{B}")
return
g = gcd(A, B)
A = A // g
B = B // g
C = B // A
E = C + 1
print(f"1/{E}", end="+")
solve(A * E - B, B * E)
for line in sys.stdin:
A, B = list(map(int, line.strip().split("/")))
solve(A, B)
标签:真分数,frac,gcd,sys,牛客,solve,file,机试,HJ82 来源: https://www.cnblogs.com/junstat/p/16177295.html