数据结构与算法【Python实现】(十)欧几里得算法

约数:如果整数a能被整数b整除,那么a叫做b的倍数,b叫做a的约数

给定两个整数a,b,两个数所有公约数中的最大值即为最大公约数

如何计算两个数的最大公约数:

欧几里得——辗转相除法

数据结构与算法【Python实现】(十)欧几里得算法

#递归算法
def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)

#非递归算法
def gcd_2(a, b):
    while b > 0:
        r = a % b
        a = b
        b = r
    return a

eg:利用欧几里得算法实现一个分数类,支持分数的四则运算

class Fraction:
    def __init__(self,a,b):  #a分子 b分母
        self.a = a
        self.b = b
        x = self.gcd(a, 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 zgs(self, a, b): #最小公倍数
        x = self.gcd(a, b)
        return (a * b ) / x


    def __add__(self, other):
        a = self.a
        b = self.b
        c = other.a
        d = other.b
        fenmu = self.zgs(b, d)
        fenzi = a * (fenmu / b) + c * (fenmu / d)
        return Fraction(fenzi, fenmu)

    def __sub__(self, other):
        a = self.a
        b = self.b
        c = other.a
        d = other.b
        fenmu = self.zgs(b, d)
        fenzi = a * (fenmu / b) - c * (fenmu / d)
        return Fraction(fenzi, fenmu)

    def __mul__(self, other):
        a = self.a
        b = self.b
        c = other.a
        d = other.b
        fenmu = b * d
        fenzi = a * c
        return Fraction(fenzi, fenmu)

    def __truediv__(self, other):
        a = self.a
        b = self.b
        c = other.a
        d = other.b
        fenmu = b * c
        fenzi = a * b
        return Fraction(fenzi, fenmu)


    def __str__(self):
        if self.b == 1:
            return "%d" % self.a
        else:
            return "%d/%d" % (self.a, self.b)

a = Fraction(2,3)
b = Fraction(1,2)
print(a/b)

上一篇:SAP- Other 在SAP中发布用户通知


下一篇:第042讲:魔法方法:算术运算 | 课后测试题及答案