Wednesday, January 9, 2013

Lowest Common Multiplier and Greatest Common Divisor in Python

Lowest Common Multiplier (LCM) and Greatest Common Divisor (GCD) can be found for any list of numbers by this code. 
LCM x GCD = FACT(x1,x2,...xn)
Here, FACT(x1,x2,...xn) is the multiplication of the input arguments x1 to xn. I used the above equation to find the GCD by calculating LCM first. However, you can calculate GCD directly using Euclid's algorithm.

Code

def lcm(x,y):
    tmp=x
    while (tmp%y)!=0:
        tmp+=x
    return tmp

def lcmm(*args):
    return reduce(lcm,args)

def fact(args):
    if len(args) == 0:
        return 1
    else:
        return args[0] * fact(args[1:])

def gcd(args):
    return fact(args)/lcmm(*args)

args=range(1,11)
print args
print 'LCM:', lcmm(*args)
print 'GCD:', gcd(args)

Euclid's Algorithm

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

Question

Find the sequence of numbers whose remainder is one less than its divisor?
Eg. Consider N, N mod x = x - 1 for x in list 1 - 20. Find the sequence of N?

Ans. Find the LCM of list 1 - 20, then N = k * LCM - 1, where k is an integer.

No comments:

Post a Comment