0

I need a good function to be able to pass a list of numbers and get the GCD or LCM from it, normally it would say:

def computeGCD(x, y): 

   while(y): 
       x, y = y, x % y 

   return x 
>>> computeGCD(30, computeGCD(54, 72))
>>> 6

But I need a function to receive a list of numbers, can anyone help?

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214

2 Answers2

0

That's what I came with when trying to solve my problem. Any thoughts? Thanks for feedback.

def lcm(nums):
    max_ = max(nums)
    i = 1
    while True:
        mult = max_ * i
        if all(mult%nr == 0 for nr in nums):
            return mult
        i += 1

>>> lcm([19, 7, 8])
>>> 1064

and

def __gcd_(x,y):
    while(y):
        x,y=y,x%y
    return x

def gcd(nums):

    if len(nums) == 2:
        return __mdc_(nums[0], nums[1])
    else:
        gcd_val = __gcd_(nums[0], nums[1])
        nums[0] = gcd_val
        del nums[1]
        return gcd(nums)

>> gcd([30, 54, 72])
>> 6
0

You can make use of functools.reduce. For example,

from functools import reduce
list_of_nums = [4, 8, 16, 20]

multiple_gcd = reduce(computeGCD, list_of_nums)  # using your implementation of computeGCD
assert multiple_gcd == 4

This works as both GCD and LCM are associative.

fractals
  • 816
  • 8
  • 23