Python Forum
math.gcd() is limited to 2 arguments - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: math.gcd() is limited to 2 arguments (/thread-20417.html)



math.gcd() is limited to 2 arguments - Skaperen - Aug-09-2019

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.


RE: math.gcd() is limited to 2 arguments - scidam - Aug-10-2019

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)



RE: math.gcd() is limited to 2 arguments - Skaperen - Aug-10-2019

yes, that is true, that's how i wrote a better gcd() that handles whatever is given to it.