简体   繁体   中英

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. How can I get the return from the if loop to become the final output of the program? We are using Euclid's algorithm to calculate in this instance.

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:

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 ( % ). 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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