What am I doing wrong with this lcm python code?

489 views Asked by At

Here is my code:

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

    elif b%a == 0:
        return a
        print a
    else:
        if a > b:
            gcd(a%b,b)
        elif b > a:
            gcd(b%a,a)
        else:
            return a
            print a
def lcm(a,b):
    if a==b:
        return a
    else:
        y = gcd(a,b)
        return (a*b)/y
        print (a*b)/y

What am I doing wrong? I keep getting an error because apparently y = gcd(a,b) is a NoneType and it must be an integer. But from what I see it is an integer.

3

There are 3 answers

0
Hyperboreus On BEST ANSWER

Put return in front of your recursive calls to gcd. Otherwise it returns None if it ends up in one of those branches.

The print statements after your returns are never reached.

0
amrx On

once a return statement is executed , the control exits from the function call. So your print statements are never executed . You should write print statement before return . Also doing a dry run with pen and paper would help the flow of execution.

0
Ray On

Actually, the code can be much simpler for gcd and lcm, since some of your base cases overlap.

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

def lcm(a, b):
    return a * b / gcd(a, b)

Don't forget: for recursive functions, you have to use return to link recursive calls.