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