Calculate the LCM of a list of given numbers in Python

This is the best way that I know of :

from math import gcd
a = [100, 200, 150]   #will work for an int array of any length
lcm = 1
for i in a:
    lcm = lcm*i//gcd(lcm, i)
print(lcm)

Hope this helps. All queries, contributions and comments are welcome :)


Works with an arbitrarily long denominator list.

from math import gcd # Python versions 3.5 and above
#from fractions import gcd # Python versions below 3.5
from functools import reduce # Python version 3.x

def lcm(denominators):
    return reduce(lambda a,b: a*b // gcd(a,b), denominators)

Example:

>>> lcm([100, 200, 300])
600

Tags:

Python