Python Program to Find the LCM of two numbers (3 Ways)
In this program, we will learn how to find the LCM of two numbers using the Python programming language.
What is LCM?
it stands for Least Common Multiple. It can be found for two or more numbers by making multiple of the numbers and then choosing the least common multiple.
Let’s take the example of 3 and 4.
Multiple of 3 : 3, 6, 9, 12, 15, 18, 21, 24,…….
Multiple of 4 : 4, 8, 12, 16, 20, 24, 28,…..
So, common multiple of 3 and 4 is 12, 24 and Least Common Multiple is 12.
Hence, LCM of 3 and 4 is 12.
We will discuss three ways to write code for it.
- Using the loop
- Using the GCD or HCF
- Using the Recursion
Python Programming Code to Find the LCM of two numbers
Using the loop
Code:-
num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) lcm = num1 if(num1 > num2) else num2 while(True): if((lcm % num1 == 0) and (lcm % num2 == 0)): print("The L.C.M. of", num1,"and", num2,"is", lcm) break lcm += 1
Ouput:-
Enter second number: 24
The L.C.M. of 18 and 24 is 72
Using the GCD or HCF
Code:-
def gcd(num1,num2): if num1%num2 == 0: # Base case return num2 else: # Iterative case return gcd(num2,num1%num2) num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) lcm = (num1*num2)//gcd(num1,num2) print("The L.C.M. of", num1,"and", num2,"is", lcm)
Output:-
Enter second number: 9
The L.C.M. of 6 and 9 is 18
Using the Recursion
Code:-
def lcm(x, y): lcm.multiple += y if((lcm.multiple % x == 0) and (lcm.multiple % y == 0)): return lcm.multiple else: return lcm(x, y) lcm.multiple = 0 num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if num1 > num2: lcm = lcm(num2, num1) else: lcm = lcm(num1, num2) print("The L.C.M. of", num1,"and", num2,"is", lcm)
Output:-
Enter second number: 55
The L.C.M. of 65 and 55 is 715
You can learn about many other Python Programs Here.
Best Books for learning Python with Data Structure, Algorithms, Machine learning and Data Science.
Amit Rawat
Latest posts by Amit Rawat (see all)
- Python Program to Print the Fibonacci Sequence (2 ways) - April 7, 2020
- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019