Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 不使用递归的GCD_Python 3.x - Fatal编程技术网

Python 3.x 不使用递归的GCD

Python 3.x 不使用递归的GCD,python-3.x,Python 3.x,下面给出的代码仅适用于某些输入,例如gcdIter(2,12),它为我提供了正确的输出,即2,但如果我作为gcdIter(220120)提供输入,它将为我提供110而不是20。我需要一些逻辑方面的帮助 def gcdIter(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if a&l

下面给出的代码仅适用于某些输入,例如gcdIter(2,12),它为我提供了正确的输出,即2,但如果我作为gcdIter(220120)提供输入,它将为我提供110而不是20。我需要一些逻辑方面的帮助

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

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    if a<b:
        while a>0:
            if b%a==0:
                print('the gcd is : '+''+str(a))
                break
            else:
                a -= 1
    else:
         while b>0:
            if a%b==0:
                print('the gcd is :'+''+str(b))
                break
            else:
                b -= 1
def gcdIter(a,b):
'''
a、 b:正整数
返回:正整数,a和b的最大公约数。
'''
如果a0:
如果b%a==0:
打印('gcd为:'+''+str(a))
打破
其他:
a-=1
其他:
当b>0时:
如果a%b==0:
打印('gcd为:'+''+str(b))
打破
其他:
b-=1
就这么简单。不需要检查
ab

就这么简单。不需要检查
ab


对不起,你的代码对我来说毫无意义。
a-=1
有什么意义?欢迎来到堆栈溢出!看起来您需要学习使用调试器。请随便吃点。如果您以后仍然有问题,请随时返回并提供更多详细信息。我只是将a的值递减,然后再次检查以获得正确答案。对不起,您的代码对我来说毫无意义。
a-=1
有什么意义?欢迎来到堆栈溢出!看起来您需要学习使用调试器。请随便吃点。如果您以后仍然有问题,请随时返回并提供更多详细信息。我只是将a的值递减,然后再次检查以获得正确答案。抱歉!!但是我没有得到这个部分“a,b=b,a%b”a,b=b,a%b只是a=b&b=a%b:)对不起!!但是我没有得到这个部分“a,b=b,a%b”a,b=b,a%b只是a=b&b=a%b的缩写形式:)
def gcdIter(a, b):
    while b:
        a, b = b, a%b
    print('the gcd is :'+str(a))