Search code examples
pythonlcm

finding the LCM using python


def multiple(a, b): """so I'm trying to return the smallest number n that is a multiple of both a and b.

for example:

multiple(3, 4) 12 multiple(14, 21) 42 """

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

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

it keeps throwing errors about indentation and logic. I don't understand why. I've tried changing the variables around too.


Solution

  • No need to find GCD, we can directly find LCM. Below code works

    def lcmof(x,y):
        res=0
        mx=max(x,y)
        mn=min(x,y)
        for i in range(1,mx+1,1):
            temp=mx*i
            try:
                if(temp%mn==0):
                    res=temp
                    break
            except ZeroDivisionError:
                res=0
                break
        return res