整数除法或模数为零

时间:2017-11-02 17:39:19

标签: python division

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

为什么它会出现错误,因为我想找到一个&的最大公约数。 B'

2 个答案:

答案 0 :(得分:0)

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

此行错误,对吧?

test = 0

您不能% 0,因为这不起作用。您想要test = atest = b而不是相反。此外,您可以test = min(a, b)。另外,使用欧几里德算法。

您不需要test = 0,因为if没有范围,但再次,只需取出if并执行test = min(a, b)

答案 1 :(得分:0)

你试图在第一次迭代中除以零,这将导致ZeroDivisionError:整数除法或模数为零

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

您需要更改代码:

b = test #should be test = b
a = test #should be test = a