Search code examples
mathgreatest-common-divisorlcm

How to get GCD and LCM of a range of numbers efficiently?


I currently use this code to find gcd and lcm

def gcd(a, b):
    while b != 0:
        a, b = b, a%b
    return a

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

But what if I want to do this for a list of numbers e.g. [4,5,7,1,5,7,10,1,16,24] etc? Am I constrained to loops?


Solution

  • As mentioned by Chris J this SO question provides the algorithm. Here is a python version of the answer that uses the reduce built-in and the fractions module that has been around since version 2.6.

    import fractions
    
    def gcd(*values):
        return reduce(fractions.gcd, values)