Python Program to Find LCM


To understand this example, you should have knowledge of following Python programming topics:
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.

Source Code to find LCM


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

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

   # choose the greater number
   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


# 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

Enter first number: 54
Enter second number: 24
The L.C.M. of 54 and 24 is 216
This program asks for two integers and passes them to a function which returns the L.C.M. In the function, we first determine the greater of the two number since the L.C.M. can only be greater than or equal to the largest number. We then use an infinite while loop to go from that number and beyond. In each iteration, we check if both the input numbers perfectly divides our number. If so, we store the number as L.C.M. and break from the loop. Otherwise, the number is incremented by 1 and the loop continues.
The above program is slower to run. We can make it more efficient by using the fact that the product of two numbers is equal to the product of least common multiple and greatest common divisor of those two numbers.

Number1 * Number2 = L.C.M. * G.C.D.
Here is a Python program to implement this.

Source Code


# Python 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


# 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))
The output of this program is same as before. 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. Click here to learn more about methods to calculate G.C.D in Python.

Comments