算法进阶03---欧几里得算法

最大公约数

# 递归求最大公约数
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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值