Sunday, 25 September 2016

Greatest common divisor using recursive method

By implementing the Euclidean algorithm, the greatest common divisor of any two numbers can be obtain through a recursive method.

Neat!


def gcdRecur(a, b):
    '''
    a, b: positive integers
    
    returns: a positive integer, the greatest common divisor of a & b.
    '''
    # Your code here
    if b>a: 
        tmp=a
        a=b
        b=tmp
    
    if (b==0):
        return a
    else:
        return gcdRecur(b, a%b)

No comments:

Post a Comment