整数除以z或模

2024-06-25 06:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

def gcdIter(a, b):

'''
a, b: positive integers

returns: a positive integer, the greatest common divisor of a & b.
'''

test = 0
if a > b:
    b = test
else:
    a = test
while test != 1:
    if a%test == 0 and b%test == 0:
        return test
    test -= 1
return 1

为什么我要求a&b的最大公约数,结果会出错呢?在


Tags: oftheintegerstestreturnifdefinteger
2条回答

您试图在第一次迭代中被零除,这将导致零除法错误:整数除法或模被零除

if a%test == 0 and b%test == 0:

您需要更改代码:

^{pr2}$
if a%test == 0 and b%test == 0:

这条线出错了,对吗?在

^{pr2}$

你不能做% 0,因为这行不通。你想做test = a和{},而不是相反。另外,你可以做test = min(a, b)。同样,使用欧几里德算法。在

你不需要test = 0,因为if没有作用域,但是,还是把if去掉,做test = min(a, b)。在

相关问题 更多 >