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的最大公约数,结果会出错呢?在
您试图在第一次迭代中被零除,这将导致零除法错误:整数除法或模被零除
您需要更改代码:
^{pr2}$这条线出错了,对吗?在
^{pr2}$你不能做},而不是相反。另外,你可以做
% 0
,因为这行不通。你想做test = a
和{test = min(a, b)
。同样,使用欧几里德算法。在你不需要
test = 0
,因为if
没有作用域,但是,还是把if
去掉,做test = min(a, b)
。在相关问题 更多 >
编程相关推荐