Python Forum
math.gcd() is limited to 2 arguments
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
math.gcd() is limited to 2 arguments
#1
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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)
Reply
#3
yes, that is true, that's how i wrote a better gcd() that handles whatever is given to it.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  isinstance() arg2 is limited to a type or a tuple of types Skaperen 5 3,788 Dec-02-2019, 06:07 PM
Last Post: Skaperen
  Distributed size limited queue implementation? johsmi96 1 1,923 May-08-2019, 07:29 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020