简体   繁体   English

在递归函数中使用欧几里得算法的问题

[英]Problem using Euclid's algorithm in recursive function

I'm a beginner learner and have been going through this code for a while now on PythonTutor and I am getting the right value for 'final' in 27 steps, but can't seem to figure out how to get the while loop to stop executing and calculating the remainders.我是初学者,现在已经在 PythonTutor 上阅读这段代码一段时间了,我在 27 个步骤中获得了“final”的正确值,但似乎无法弄清楚如何让 while 循环停止执行和计算余数。 How can I get the return from the if loop to become the final output of the program?如何从 if 循环中获取返回值以成为程序的最终输出? We are using Euclid's algorithm to calculate in this instance.在这种情况下,我们使用 Euclid 算法进行计算。

def gcdRecur(a, b):
    '''
    a, b: positive integers
    
    returns: a positive integer, the greatest common divisor of a & b.
    '''
final=''    
high=max(a,b)
    result=min(a,b)
    while high%result>0:
        result-=1
        return result*gcdRecur(b,(a%b))
    if high%result==0:
        final=result
        return final
a=1071 
b=462
final_ans=gcdRecur(a,b)
print(final_ans)
        

I think you have your wires crossed Euclid-wise.我认为你的电线越过了欧几里得。 If you insist that the input be positive integers (ie not 0 nor negative) then you can use Euclid's subtraction-based algorithm:如果你坚持输入是正整数(即不是 0 也不是负数),那么你可以使用 Euclid 的基于减法的算法:

def gcdRecur(a, b):
    '''
    a, b: positive integers
    returns: a positive integer, the greatest common divisor of a & b.
    '''

    if a == b:
        return a

    if a > b:
        a -= b
    else:
        b -= a

    return gcdRecur(a, b)

and avoid the min() , max() and modulus ( % ).并避免min()max()和模数 ( % )。 If you use the modulus variant of Euclid's algorithm, then you don't require as tight constraint on the input values and it can be expressed recursively as simply:如果您使用 Euclid 算法的模数变体,那么您不需要对输入值进行如此严格的约束,并且可以简单地递归表示:

def gcdRecur(a, b):
    return a if not b else gcdRecur(b, a % b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM