Python :: lcm

Returns the least common multiple of two or more numbers.

Use the greatest common divisor (GCD) formula and the fact that lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple. The GCD formula uses recursion.

Uses reduce function from the inbuilt module functools. Also defines a method spread for javascript like spreading of lists.

from functools import reduce

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
    return ret

def lcm(*args):
    numbers = []

    def _gcd(x, y):
        return x if not y else _gcd(y, x % y)

    def _lcm(x, y):
        return x * y / _gcd(x, y)

    return reduce((lambda x, y: _lcm(x, y)), numbers)
lcm(12, 7) # 84
lcm([1, 3, 4], 5) # 60

Leave a Reply

Your email address will not be published. Required fields are marked *