Python | Find LCM using function

Let us take a look t methods that we have to find the LCM using functions

Method 1: Using the divide operator

def calc_LCM(x, y):
   if x > y:
       greater = x
   else:
       greater = y

   while(True):
       if((greater % x == 0) and (greater % y == 0)):
           lcm = greater
           break
       greater += 1

   return lcm

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

print("The L.C.M. is", calc_LCM(num1, num2))

Output:

Enter the first number: 64
Enter the second number: 56
The L.C.M. is 448

Explanation:

Here we compared the value passed to the function i.e x and y if x > y then we assign the value of x in a greater variable and the same goes for y. Now we used the while loop and check the condition
(greater % x == 0) and (greater % y == 0), if this satisfies then and then we assign the value of greater to the lcm variable or else we increment greater and continue on with the loop.

Method 2: Using reduce() function

def check_LCM(a, b):
    if a > b:
        greater = a
    else:
        greater = b

    while True:
        if greater % a == 0 and greater % b == 0:
            lcm = greater
            break
        greater += 1

    return lcm

def calc_LCM(your_list):
    return reduce(lambda x, y: check_LCM(x, y), your_list)

ans = calc_LCM([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The LCM is: ",ans)

Method 3: Using recursion

def calc_LCM(n, m):
    if m == 0:
        return n
    return calc_LCM(m, n % m)

A = [100, 205, 12 , 15, 5, 19]
lcm = 1
for i in A:
    lcm = lcm * i // calc_LCM(lcm, i)
    
print("The LCM is: ", lcm)

Explanation:

Here we used a for loop, wherein we did the floor division between the expression calc_LCM(lcm, i)and the output of calc_LCM(lcm, i). This will again call the function and in the second iteration the value inside the lcm variable will be the round-off whole number computed by lcm * i // calc_LCM(lcm, i)

Method 4: Using NumPy

import numpy as np
result = np.lcm(120, 200)

These above are some of the methods in order to compute the LCM. That’s all for this article, we will be back with another problem-solving article.

Share:

Author: Dhvanil V