欧几里得算法python实现
计算两个数的最大公约数:辗转相除法(欧几里得算法)。
gcd(a, b) = gcd(b, a mod b)
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
# print(gcd(12, 120))
class Fraction:
def __init__(self, a, b):
self.a = a
self.b = b
self.maximum_convention = self.gcd(self.a, self.b)
self.a /= self.maximum_convention
self.b /= self.maximum_convention
def least_common_multiple(self, x, y):
maximum_convention = self.gcd(x, y)
return maximum_convention
def __add__(self, other):
# other 表示另一个对象,即计算 a/b + other.a/other.b
a = self.a
b = self.b
c = other.a
d = other.b
fenmu = self.least_common_multiple(b,d)
fenzi = a*fenmu/b + c*fenmu/d
return Fraction(fenzi, fenmu)
def gcd(self, x, y):
while y > 0:
c = x % y
x = y
y = c
return x
def __repr__(self):
return f'分数:{self.a}/{self.b}'
fun = Fraction(1,2)
f2 = Fraction(1, 4)
print(fun+f2)