algorithm – Python gcd for list

algorithm – Python gcd for list

here is the piece of code, that I used:

from fractions import gcd
from functools import reduce
def find_gcd(list):
    x = reduce(gcd, list)
    return x

As of python 3.9, python got built-in support for calculating gcd over a list of numbers.

import math
A = [12, 24, 27, 30, 36]
print(math.gcd(*A))

Output:

3

algorithm – Python gcd for list

def gcd (a,b):
    if (b == 0):
        return a
    else:
         return gcd (b, a % b)
A = [12, 24, 27, 30, 36]
res = A[0]
for c in A[1::]:
    res = gcd(res , c)
print res

ideone link

Leave a Reply

Your email address will not be published.