--- 分数加法 --- 通分 - 计算分母的最小公倍数 算出分子
class Fraction(object):
def __init__(self, a, b):
x = self.gcd(a, b)
self.a = a // x
self.b = b // x
@staticmethod
def gcd(a, b):
"""最大公约数"""
while b > 0:
r = a % b
a, b = b, r
return a
@staticmethod
def lcm(a, b):
"""最小公倍数"""
return a * b // Fraction.gcd(a, b)
def __str__(self):
return f'{self.a} / {self.b}'
def __add__(self, other):
a = self.a
b = self.b
c = other.a
d = other.b
# 通分
denominator = self.lcm(b, d)
# 通分后,算出分子
numerator = a * denominator // b + c * denominator // d
return Fraction(numerator, denominator)
a = Fraction(1, 3)
b = Fraction(1, 2)
print(a + b)