编程语言
首页 > 编程语言> > 数据结构与算法【Python实现】(十)欧几里得算法

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

作者:互联网

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

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

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

欧几里得——辗转相除法

#递归算法
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)

标签:__,return,Python,self,算法,other,fenmu,数据结构,def
来源: https://blog.csdn.net/hhhxykeke/article/details/122710340