geek_code - 2 months ago 9

Python Question

I wrote a code which calculates the GCD of two numbers. The gcd of (24,12) is 12. The function

`compute_gcd`

`none`

`compute_gcd`

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()

Answer

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()
```

Source (Stackoverflow)

Comments