最大公约数
# 递归求最大公约数
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a % b)
print(gcd(16,4))
# 非递归求最大公约数
def gcd_no(a,b):
while b > 0: # b>0时继续循环
r = a % b
a=b
b=r
return a # b=0时退出循环,
print(gcd(16,4))
应用:实现分数计算
利用欧几里得算法实现一个分数类,支持分数的四则运算。
class Fraction:
def __init__(self,a,b):
self.a=a
self.b=b
x=self.gcd(self.a,self.b)
# 分数约分
self.a /=x
self.b /=x
def gcd(self,a,b):
'''求最大公约数'''
while b>0:
r=a%b
a=b
b=r
return a
def mcm(self,a,b):
'''
求最小公倍数
12 16 -> 4
3 * 4 * 4 = 48 # 48就是最小公倍数
'''
x = self.gcd(a,b)
return (a / x) * (b / x) * x # 或者 a*b/x
def __add__(self,other):
'''分数相加'''
a = self.a
b = self.b
c = other.a
d = other.b
denominator = self.mcm(b,d) # 通分
numerator = a*denominator/b + c*denominator/d
return Fraction(numerator,denominator)
def __mul__(self, other):
'''分数乘法'''
a = self.a
b = self.b
c = other.a
d = other.b
return Fraction(a*c,b*d)
def __str__(self):
return "%d / %d"%(self.a,self.b)
a=Fraction(1,3)
b=Fraction(1,2)
print(a+b)
print(a*b)