Question

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 !!!

Was it helpful?

Solution

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

OTHER TIPS

a simple solution is like this

def gcd(a, b):
    #find the gcd of a,b,None if not found
    miner = min(a, b)
    gcd = None
    for i in xrange(1, miner+1):
        if(a % i == 0 and b % i == 0):
            gcd = i
    return gcd    

now if a > b, you can get this from google gcd(a,b) = gcd(a%b,b) you can take a while loop to improve the performance of function, you can try it

You guys are amazing!!!! Thanks for all the answers. It turned out I needed to use While loop of minus 1 until the min(a, b) reach to gcd.

Though your answers seem much simpler, answer of this problem set is below

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

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    x = min(a, b)

    # Keep looping until testValue divides both a & b evenly
    while a % x != 0 or b % x != 0:
        x -= 1

    return x

Again, thanks for all!!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top