python – Built-in module to calculate the least common multiple

python – Built-in module to calculate the least common multiple

In Python 3.8 and earlier

There is no such thing built into the stdlib.

However, there is a Greatest Common Divisor function in the math library. (For Python 3.4 or 2.7, its buried in fractions instead.) And writing an LCM on top of a GCD is pretty trivial:

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

Or, if youre using NumPy, its come with an lcm function for quite some time now.

In Python 3.9+

This is available as math.lcm(). It also takes any length of arguments, allowing you to find the lowest common multiple of more than 2 integers.

python – Built-in module to calculate the least common multiple

Try this instead:

def lcm(x, y):
    from fractions import gcd # or can import gcd from `math` in Python 3
    return x * y // gcd(x, y)

Leave a Reply

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