Skip to content
Home » Blog » Python Program to Find LCM

Python Program to Find LCM

find lcm in Python

In this program, you’ll learn how to find Least Common Multiple or find LCM

To properly understand this example of how to find LCM in Python, you should have the knowledge of following Python programming topics:

  1. Python while Loop
  2. Python Functions
  3. Python Function Arguments
  4. Python User-defined Functions

Before we start with code lets first understand what is Least Common Multiple (LCM).

A common multiple is a number that is a multiple of two or more numbers. The common multiples of 3 and 4 are 0, 12, 24, ….

The least common multiple (LCM) of two numbers is the smallest number (not zero) that is a multiple of both.

Find LCM in Python

The least common multiple (L.C.M.) of two numbers is the smallest positive integer that is perfectly divisible by the two given numbers.

For example, the L.C.M. of 12 and 14 is 84.

Program to find the L.C.M. of two input number

# define gcd function
def gcd(x, y):
   """This function implements the Euclidian algorithm
   to find G.C.D. of two numbers"""

   while(y):
       x, y = y, x % y

   return x

# define lcm function
def lcm(x, y):
   """This function takes two
   integers and returns the L.C.M."""

   lcm = (x*y)//gcd(x,y)
   return lcm

# change the values of num1 and num2 for a different result
num1 = 54
num2 = 24 

# uncomment the following lines to take input from the user
#num1 = int(input("Enter first number: "))
#num2 = int(input("Enter second number: "))

print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))

Output:

The L.C.M. of 54 and 24 is 216

Note: Here to test this program, change the values of num1 and num2.

We have two functions gcd() and lcm(). We require G.C.D. of the numbers to calculate its L.C.M.

So, lcm() calls the function gcd() to accomplish this. G.C.D. of two numbers can be calculated efficiently using the Euclidean algorithm.

Related Program

Ask your questions and clarify your/others doubts on How to find lcm in Python by commenting. Python Documentation