0

I am trying to calculate a GCD of 2 numbers, the following code block works fine, I am using recursion, but when I am trying to return a value I am not able to do so, return a results in None

def gcd(a,b):
    if b == 0:
        print a
        return a   # This is not working 
    else:
        gcd(b,a%b)

XX = gcd(3, 5)
print (XX)

Output:

1
None
2
  • A function returns None is no explicit return statement is executed. Commented Nov 15, 2018 at 17:21
  • your recursive call to gcd needs to be returned, Like return gcd(b,a%b) Commented Nov 15, 2018 at 17:21

2 Answers 2

0

Your code

def gcd(a,b):
    if b == 0:
        print a
        return a   # This is not working 
    else:
        gcd(b,a%b)

XX=gcd(3,5)
print (XX)

will not work, because you are missing the return statement in the line gcd(b,a%b). So it should be

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

print(gcd(12, 4))

By the way - if possible, don't code things yourself, use the predefined library:

from fractions import gcd
print(gcd(4, 12))
Sign up to request clarification or add additional context in comments.

Comments

0

Your recursion will not work... you are missing a return statement and also the algorithm does not work...

This is what a recursive gcd could look like:

def gcd(a,b):
    r = a % b
    if r == 0:
        return a
    elif r == 1:
        return 1
    return gcd(b, r)

and here a non-recursive gcd:

def gcd(a, b):
   while b:
       a, b = b, a % b
   return a

also note that you could just use math.gcd.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.