1

I wrote a code which calculates the GCD of two numbers. The gcd of (24,12) is 12. The function compute_gcd computes the GCD and returns it which gets printed in the main function. However, the output is none when I return it to the main function and it is 12 when I print it in the compute_gcd function itself.

Where am I going wrong while returning the GCD?

def compute_gcd(a,b):
    if(b==0):
        return a             # Prints 12 if I replace with print a
    else:
        compute_gcd(b,a%b)

def main():
    a=24
    b=12 
    print compute_gcd(a,b)   # Prints none

main()
sagar_jeevan
  • 761
  • 5
  • 16
  • 34

3 Answers3

4

You forgot to put a return in the else branch. This works:

def compute_gcd(a,b):
    if b == 0:
        return a
    else:
        return compute_gcd(b,a%b)

def main():
    a=24
    b=12

    print compute_gcd(a,b)   # Prints 12

main()
David Gomes
  • 5,644
  • 16
  • 60
  • 103
0

try this ... you have to do a return inside the else statement

def compute_gcd(a,b):
    if(b==0):
        return a
    else:
        return compute_gcd(b,a%b)

def main():
    a = 24
    b = 12

    print(compute_gcd(a,b))

main()
caldera.sac
  • 4,918
  • 7
  • 37
  • 69
-2

Your else condition has no return hence output is none. If you change that to

else:
  return compute_gcd(b,a%b)

You'll get 12.

mr-karan
  • 203
  • 4
  • 11