最大公约数gcd算法原理与实现

这是欧几里得算法:
证明的视频链接

image.png

# 递归版本
def gcd2(num1,num2):
    remainder = num2%num1
    if remainder == 0:
        return num1
    else:
        return gcd2(remainder,num1)


def gcd(num1,num2):
    if num1 < num2:
        quotient = num2
        remainder = num1
    elif num1 > num2:
        quotient = num1
        remainder = num2
    else:
        return num1

    while remainder > 0:
        temp = remainder
        remainder = quotient % remainder
        quotient = temp

    return quotient


def main():
    ret = gcd2(15,25)
    print(ret)


if __name__ == '__main__':
    main()

你可能感兴趣的:(最大公约数gcd算法原理与实现)