3

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

Óscar López
  • 232,561
  • 37
  • 312
  • 386
Hiro Gotanda
  • 129
  • 2
  • 8
  • 1
    If we do x-1 from the else, how should that impact the a and b parameters? You may want to re-evaluate your algorithm. For recursion the else will call the function again. – James Black Jun 15 '13 at 01:21
  • A side note: you don't need to take up five lines of comments after the `def gcdIter()` part; one line above the code definition is enough. – TakeS Jun 15 '13 at 02:26

3 Answers3

6

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
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

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

michaelyin
  • 83
  • 3
  • 9
0

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

Hiro Gotanda
  • 129
  • 2
  • 8
  • In your question, you stated that you were "stacked making recursion code". This is not recursive code, it's iterative! – Óscar López Jun 15 '13 at 15:07