Example HTML page

A Python program to find LCM(using math module)

In the earlier posts we have seen the ways to evaluate the LCM.You can refer those from the following links.

Method 1: https://www.vmsclass.in/index.php/a-python-program-to-find-lcmusing-loops/

Method 2:https://www.vmsclass.in/index.php/a-python-program-to-find-lcmusing-functions/

In this post we will see one more method to find LCM.

Using ‘math’ module

To find LCM by using math module we have a formula and is as follows:

n1 * n2 =  LCM * GCD


LCM  =   (n1 * n2)/GCD of n1 and n2

Let’s write the program using this formula.

import math
def get_lcm(n1,n2):
  #find gcd
  gcd = math.gcd(n1,n2)
  result = (n1*n2)/gcd
  return result
n1 = 6
n2  = 8
lcm = get_lcm(n1,n2)
print("LCM of",n1, "and", n2, "is","  =  ", lcm)


LCM of 6 and 8 is   =   24.0


In the above program we are importing a math module and then creating a function definition as “get_lcm” by passing n1 and n2 as its parameters. Now, we are calculating GCD using math module. After knowing GCD we apply the formula and the result is stored in “result” variable. Assigning values to n1 and n2 values and calling the function definition. Finally you will be displayed the output of LCM.

What if there are more than two numbers. So here is the program for it.

#To find LCM of more than two numbers.

from math import gcd
L = [4,6,12,26]   
lcm = L[0]
for a in L[1:]:
  lcm = int(lcm*a/gcd(lcm, a))
print("LCM for the numbers in the list is =  ", lcm)


LCM for the numbers in the list is =   156


To find LCM for more than two numbers we create a list of numbers and are stored in variable “L”. We are storing the first element of the list in a variable “lcm”. Perform looping on every element in the list. Inside the loop we are applying a formula lcm = int(lcm*a/gcd(lcm, a)). After completion of loop the LCM of numbers in the list will be displayed.


Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest