user3103718
user3103718

Reputation: 63

What am I doing wrong with this lcm python code?

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.

Upvotes: 1

Views: 483

Answers (3)

Ray
Ray

Reputation: 2510

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.

Upvotes: 2

amrx
amrx

Reputation: 713

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.

Upvotes: 0

Hyperboreus
Hyperboreus

Reputation: 32429

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.

Upvotes: 2

Related Questions