5/07/2016

Greatest Common Divisor function with multiple arguments in python

import math 
import fractions
def gcdm(*args):
    UaS = sorted(list(set(list(args))))
    if len(UaS) == 1:
        return list(UaS)[0]
    if len(UaS) == 2:
        return fractions.gcd(UaS[0],UaS[1])
    if len(UaS) >= 3:
        pair = fractions.gcd(UaS[0],UaS[1])
        print(pair)
        for i in range(2,len(UaS)):
            pair = fractions.gcd(pair,UaS[i])
        return pair
    return 0
 
print(gcdm(10,20,30,40,50)) == 10

You can do it with fractions or math module which both have gcd function.

No comments:

Post a Comment