Atila
Atila

Reputation: 81

recursion stack misleading output

I have some confusion in recursion. I am not understanding that how the print is working

def gcd(a, b):
    # Everything divides 0
    print (a, b)
    if (b == 0):
        print ("I am here")
        return a
    return gcd(b, a % b)


# Driver program to test above function
a = 13
b = 24
if (gcd(a, b)):
    print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
    print('not found')

13 24

24 13

13 11

11 2

2 1

1 0

I am here

13 24 #----- Need to know from here how the printing is working, how it is 13 and 24 ? how the stack is keeping 13, 24 at this point ?

24 13

13 11

11 2

2 1

1 0

I am here

GCD of 13 and 24 is 1

Upvotes: 0

Views: 39

Answers (1)

Chris Doyle
Chris Doyle

Reputation: 11968

your issue of being printed again is cause you call the function twice.

def gcd(a, b):
    # Everything divides 0
    print ("input received is", a, b)
    if (b == 0):
        print ("I am here")
        return a
    return gcd(b, a % b)


# Driver program to test above function
a = 13
b = 24
if (gcd(a, b)):        #<------you call the function here and it does all the prints
    print('GCD of', a, 'and', b, 'is', gcd(a, b)) #<----then you call it again here so prints again
else:
    print('not found')

Instead call the function once and capture the return value

def gcd(a, b):
    # Everything divides 0
    print ("input received is", a, b)
    if (b == 0):
        print ("I am here")
        return a
    return gcd(b, a % b)


# Driver program to test above function
a = 13
b = 24
result = gcd(a, b)   #<-----call the function once and store the result
if (result):
    print('GCD of', a, 'and', b, 'is', result) #<---print the result
else:
    print('not found')

Upvotes: 1

Related Questions