我在麻省理工学院6.00学习Python,并堆叠生成递归代码。 我唯一想做的就是重复从x中减去1,但不知道该怎么做。。在
这是我的密码
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
x = min(a, b)
if max(a, b) % min(a, b) == 0:
return x
else:
return #What comes to iterate -1 from x
请帮忙!!!在
你们太棒了!!!!谢谢你的回答。 结果我需要使用While循环-1,直到最小值(a,b)达到gcd。在
下面的答案看起来简单多了
再次感谢大家!!!在
您的代码过于复杂,请尝试从wikipedia改编的递归实现:
你似乎在寻找一个迭代的解决方案(这个问题是误导性的)。如果是这样的话,这里有两个可能的实现,也改编自维基百科:
^{pr2}$一个简单的解决方案是这样的
现在如果a>;b,你可以从google得到这个 gcd(a,b)=gcd(a%b,b) 你可以用while循环来提高函数的性能,你可以试试
相关问题 更多 >
编程相关推荐