Hello. I am trying to understand Recursives. Below is a code given us while taking a course. Can anyone explain to me (map out) what is going on inside this code step by step? the code gives the greatest common denominator. The answer is 4. I have been trying to work this out on my white board for the past several hours. I am just unclear as to what is going on inside to get this answer. Pete
def gcdRecur(a,b):
if b == 0:
return a
return gcdRecur(b, a%b)
print(gcdRecur(8,12))
gcdRecur receives two arguments, so would be called like gdcRecur(value1, value2).
obviously if value2 (b) is 0 a is the answer, and is returned, otherwise the function
keeps calling itself this time with value1 being the old value2 and value 2 being the division remainder of value1/value2
the best way to see this, is to add some print statements (and an iteration counter)
so modify the code a bit (to include iteration count):
def gcdRecur(count, a,b):
print('iteration: {}, a: {}, b: {}'.format(count, a, b))
if b == 0:
return a
return gcdRecur(count + 1, b, a%b)
print('results: {}'.format(gcdRecur(1, 8, 12)))
results:
Output:
iteration: 1, a: 8, b: 12
iteration: 2, a: 12, b: 8
iteration: 3, a: 8, b: 4
iteration: 4, a: 4, b: 0
results: 4
Thank you Larz60+
I will probably look at this all day to understand and comprehend. I will also incorporate an iteration counter into those coding problems I don't understand. I can't wait to start testing this to get a better understanding of the internal workings of this code. Thanks again for the help. Pete