Monday, January 5, 2009

Least common multiple for 3 or more numbers - Stack Overflow


Least common multiple for 3 or more numbers - Stack Overflow
: "def gcd(a, b):
'''Return greatest common divisor using Euclid's Algorithm.'''
while b:
a, b = b, a % b
return a

def lcm(a, b):
'''Return lowest common multiple.'''
return a * b // gcd(a, b)

def lcmm(*args):
'''Return lcm of args.'''
return reduce(lcm, args)

Usage:

>>> lcmm(100, 23, 98)
112700
>>> lcmm(*range(1, 20))
232792560

reduce() works something like that:

def reduce(callable, iterable, ini=None):
iterable = iter(iterable)

ret = iterable.next() if ini is None else ini

for item in iterable:
ret = callable(ret, item)

return ret"

No comments: