-1

Here is the code:

#this file finds the gcd(a, b) using the euclidian algorithm
#uses the fact that, gcd(a, b) = gcd(rem(b,a), a)
def rem(a, b):
    if(a - b > b):
        rem(a-b, b)
    return a-b
#finds the gcd of a,b. Make sure a<b.
def gcd(a, b):
    if(a != 0):
        gcd(rem(b, a), a)
    else:
        print(a, b)
        return b

print(gcd(84, 126))

Here is what it outputs:

0 42
None

I'm confused because before the return statement it prints (a,b) and it prints out b as 42. But the return value on the next line is None. Can someone explain what is happening here?

zbloomer
  • 1
  • 2

1 Answers1

0

When you hit the if case in gcd, you aren't returning anything. If you add a return like this:

def gcd(a, b):
    if(a != 0):
        return gcd(rem(b, a), a) # return here
    else:
        print(a, b)
        return b

you will get 42 as you expect, instead of None.

edit: I agree with user3840170's answer in the comments -- wasn't trying to copy that, I must have been formatting my answer while that was posted :)

charlie
  • 26
  • 3