How to Calculate the Least Common Multiple in Python


The challenge

Write a function that calculates the least common multiple of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return 1.

The solution in Python code

Option 1:

from math import gcd
def lcm(*args):
    lcm=1
    for x in args:
        if x!=0:
            lcm=lcm*x//gcd(lcm,x)
        else:
            lcm=0
    return lcm

Option 2:

def lcm(*args):
    gcd = lambda m,n: m if not n else gcd(n,m%n)
    return reduce( lambda x, y: x*y/gcd(x, y), args)

Option 3:

def lcm(*args):
    args = set(args)  
    if 0 in args:
        return 0
    x = max(args)
    y = x
    args.remove(x)
    while any(x % z for z in args):
        x += y
    return x

Test cases to validate our solution

@test.describe('Example Tests')
def example_tests():
    test.assert_equals(lcm(2,5),10)
    test.assert_equals(lcm(2,3,4),12)
    test.assert_equals(lcm(9),9)
    test.assert_equals(lcm(0),0)
    test.assert_equals(lcm(0,1),0)