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

2024-09-26 17:55:00 发布

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

我在麻省理工学院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

请帮忙!!!在


Tags: oftheintegers代码密码returndefinteger
3条回答

你们太棒了!!!!谢谢你的回答。 结果我需要使用While循环-1,直到最小值(a,b)达到gcd。在

下面的答案看起来简单多了

def gcdIter(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    x = min(a, b)

    # Keep looping until testValue divides both a & b evenly
    while a % x != 0 or b % x != 0:
        x -= 1

    return x

再次感谢大家!!!在

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

def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)

你似乎在寻找一个迭代的解决方案(这个问题是误导性的)。如果是这样的话,这里有两个可能的实现,也改编自维基百科:

^{pr2}$

一个简单的解决方案是这样的

def gcd(a, b):
    #find the gcd of a,b,None if not found
    miner = min(a, b)
    gcd = None
    for i in xrange(1, miner+1):
        if(a % i == 0 and b % i == 0):
            gcd = i
    return gcd    

现在如果a>;b,你可以从google得到这个 gcd(a,b)=gcd(a%b,b) 你可以用while循环来提高函数的性能,你可以试试

相关问题 更多 >

    热门问题