Python Forum

Full Version: math.gcd() is limited to 2 arguments
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
math.gcd() is limited to 2 arguments even though there are times the GCD is needed for 3 or more numbers. and LCM (Least Common Multiple) is related and probably needed at least as much if not more, but is not available in any module. they should add math.lcm() and make it and math.gcd() support any number of ints. i guess i need to write some code.
lcm is closely related to lcd and using reduce from functools these functions could be generalized to process any
number of values at a time, e.g.

from functools import reduce
from math import gcd

def multiple_gcd(*numbers):
    return reduce(gcd, numbers)

def lcm(a, b):
    return int(a * b / gcd(a, b))

def multiple_lcm(*numbers):
    return reduce(lcm, numbers)
yes, that is true, that's how i wrote a better gcd() that handles whatever is given to it.