Python program to find LCM of two numbers

Python program to find LCM of two numbers

LCM stands for Least Common Multiple.  LCM of two numbers is the smallest number that can be divisible by both numbers. 

For example,

Consider 10 and 12,

Factors of 10 => 2, 5

Factors of 12 => 2, 2, 3

LCM of 10, 12 => 2 x 2 x 3 x 5 = 60

Procedure :

1. Start.

2. Get the two numbers as input from the user.

3. Define a function for calculating lcm.

4. Find the greatest of two numbers.

5. loop(true)

  •     if (max_elt%n1 = 0) and (max_elt%n2 = 0)
                => lcm = max_elt
                => break the loop
  •     increment max_elt
6. Return lcm

7. Call the function to calculate the lcm by passing the two numbers as arguments.

8. print the lcm.

9. End.

        

Code :

#function for lcm of two numners

def calc_lcm(num_1, num_2):

#find the greatest element

if (num_1 > num_2):

max_elt = num_1

else :

max_elt = num_2

while(True):

#number that is divisible by both the numbers

if((max_elt%num_1==0)and (max_elt%num_2==0)):

lcm = max_elt

break

max_elt = max_elt+1

return lcm

#get the first number as input from user

num_1 = int(input("Ener the first number : "))

#get the second number as input from user

num_2 = int(input("Ener the second number : "))

#find the lcm by calling the function to calculate lcm

lcm = calc_lcm(num_1, num_2)

#print the value of lcm

print("LCM = ", lcm)

Sample input 1 :

n1 = 8

n2 = 6

Sample ouput 1 :

LCM = 24

Sample input 2 :

n1 = 5

n2 = 15

Sample ouput 2 :

LCM = 15

Output screenshot :

LCM in python
LCM - Output




Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

ginortS in Python - HackerRank solution