The problem is to find LCM of two numbers. I have tried to solve the problem in two ways. First by using the LCM formula :
LCM (a,b)= a*b/GCD(a,b).
Second, by finding out the multiples of each number and then finding the first common multiple. Below are the codes that I have written:
Code 1:
#Using the LCM formula LCM = a*b / gcd(a,b)
def LCM(x , y):
""" define a function LCM which takes two integer inputs and return their LCM using the formula LCM(a,b) = a*b / gcd(a,b) """
if x==0 or y == 0:
return "0"
return (x * y)/GCD(x,y)
def GCD(a , b):
""" define a function GCD which takes two integer inputs and return their common divisor"""
com_div =[1]
i =2
while i<= min(a,b):
if a % i == 0 and b % i ==0:
com_div.append(i)
i = i+1
return com_div[-1]
print LCM(350,1)
print LCM(920,350)
Code 2:
#Finding the multiples of each number and then finding out the least common multiple
def LCM(x , y):
""" define a function LCM which take two integerinputs and return their LCM"""
if x==0 or y == 0:
return "0"
multiple_set_1 = []
multiple_set_2 = []
for i in range(1,y+1):
multiple_set_1.append(x*i)
for j in range(1,x+1):
multiple_set_2.append(y*j)
for z in range (1,x*y+1):
if z in multiple_set_1:
if z in multiple_set_2:
return z
break
print LCM(350,450)
I want to know which one of them is a better way of solving the problem and why that is the case. Also suggest what other border cases should be covered.