;

Python Program to Find the LCM of two Numbers


Tutorialsrack 22/04/2020 Python

In this Python program, we will learn how to find the LCM(Least Common Multiple) of two numbers. 

What is LCM?

The LCM of the two numbers is the smallest positive integer that is divisible by both the given numbers. For example, the L.C.M. of 5 and 6 is 30.

Here is the code of the program to find the LCM(Least Common Multiple) of two numbers. 

Program 1: Python Program to Find the LCM using if..else statement and while Loop

Python Program to Find the LCM using if..else statement and while Loop
# Python Program to Find the LCM using if..else statement and while Loop

# Define a Function to Calculate LMC
def compute_LCM(x, y):

   # 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

# To Take Input from the User
num1 = int(input("Enter the First Number: ")) 
num2 = int(input("Enter the Second Number: "))

print("The L.C.M. of {0} and {1} is {2}".format(num1, num2, compute_LCM(num1, num2)))
Output

Enter the First Number: 6

Enter the Second Number: 12

The L.C.M. of 6 and 12 is 12

Program 2: Python Program to Find the LCM Using GCD

Python Program to Find the LCM Using GCD
# Python Program to Find the LCM Using GCD

# Define a function To Calculate GCD 
def compute_GCD(x, y):

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

# Define a function To Caluclate LCM using GCD Function
def compute_LCM(x, y):
   lcm = (x*y)//compute_GCD(x,y)
   return lcm

# To Take Input from the User
num1 = int(input("Enter the First Number: ")) 
num2 = int(input("Enter the Second Number: "))

print("The L.C.M. of {0} and {1} is {2}".format(num1, num2, compute_LCM(num1, num2)))
Output

Enter the First Number: 6

Enter the Second Number: 12

The L.C.M. of 6 and 12 is 12

 

Enter the First Number: 6

Enter the Second Number: 5

The L.C.M. of 6 and 5 is 30


Related Posts



Comments

Recent Posts
Tags