Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can not make my code iterate x -= 1

I am learning Python at MIT 6.00 and stacked making recursion code. Only thing I want to do is just iterate deduct 1 from x, but don't know what to do..

Here is my code

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

Please help !!!

like image 295
Hiro Gotanda Avatar asked Dec 05 '25 07:12

Hiro Gotanda


1 Answers

Your code is overly complicated, try this recursive implementation adapted from wikipedia:

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

It seems that you were looking for an iterative solution (the question is misleading). If that was the case, here are a couple of possible implementations, also adapted from wikipedia:

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def gcd(a, b):
    while a != b:
        if a > b:
            a -= b
        else:
            b -= a
    return a
like image 76
Óscar López Avatar answered Dec 09 '25 17:12

Óscar López