2

I'm new to python and I tried creating a GCD function using Eucliean's Algorithm. But any time I try to print the answer, it returns none. May someone let me know what I'm doing wrong.

Code:

def gcd(a,b):
    if a - b != 0:
        b = b - a
        b = abs(b)
        if a > b:
            a,b = b, a
            return gcd(a,b)
            
        else:
            gcd(a,b)
    else: 
        print(a)

x = input("Give First Num... ")

y = input("Give Second Num... ")

answer = gcd(int(x), int(y))

print("GCD = {}".format(answer))

Console:

120
GCD = None
Sercan
  • 3,878
  • 3
  • 12
  • 31
MizanTech
  • 39
  • 3
  • 1
    No part of this code ever actually `return`s a greatest common denominator. – user2357112 Jan 12 '22 at 06:10
  • 1
    The only place in the function that returns something is the first recursive call, so ultimately it will just be returning `None`. Consider a simple case where `a = b = 1`. The code falls through to the top-level `else`, prints `a` (i.e. `1`), and then implicitly returns `None`. Change `print(a)` to `return a` to fix it. Then look at the second recursive call, `gcd(a,b)`. This calls itself, discards the result, and again implicitly returns `None`. Change `gcd(a,b)` to `return gcd(a,b)`. – Tom Karzes Jan 12 '22 at 06:16

2 Answers2

1
def gcd(a,b):
    if a - b != 0:
        b = b - a
        b = abs(b)

        if a > b:
            a,b = b, a
            return gcd(a,b)

        else:
            return gcd(a,b)
    else:
        return a

x = input("Give First Num... ")

y = input("Give Second Num... ")

answer = gcd(int(x), int(y))

print(answer)
print("GCD = {}".format(answer))

In the last "else", put the return before print(), because when you use a print and you want to get the value, that does not return but only print (by the last condition), you should have to get the None value.

The Amateur Coder
  • 596
  • 1
  • 8
  • 26
Payload
  • 29
  • 1
  • 3
1

To return something, there is just a minor adjustment to make on your code :

def gcd(a,b):
    if a - b != 0:
        b = b - a
        b = abs(b)
        if a > b:
            a,b = b, a
            return gcd(a,b)
            
        else:
            return gcd(a,b)
    else: 
        return a

Written this way, your function will always return something assigned to answer.

tlentali
  • 3,250
  • 2
  • 11
  • 20