我不能让我的代码迭代x - = 1

Hir*_*nda 3 python iteration recursion python-2.7 greatest-common-divisor

我正在麻省理工学院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
Run Code Online (Sandbox Code Playgroud)

请帮忙 !!!

Ósc*_*pez 6

您的代码过于复杂,请尝试从维基百科改编的递归实现:

def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)
Run Code Online (Sandbox Code Playgroud)

您似乎在寻找迭代解决方案(这个问题具有误导性).如果是这种情况,这里有几个可能的实现,也改编自维基百科:

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def gcd(a, b):
    while a != b:
        if a > b:
            a -= b
        else:
            b -= a
    return a
Run Code Online (Sandbox Code Playgroud)