Python Program to Find the LCM of Two Numbers
In this tutorial, we will discuss a Python program to find the LCM of two given numbers.
Before going to the program first, let us understand what is Least Common Multiple (LCM).
Least Common Multiple(LCM):
- The LCM of two numbers is the smallest positive integer that is divisible by both numbers.
Related: Python Program to Find GCD of Two Numbers using the Euclidean Algorithm
Program code to find LCM of two numbers in Python
# LCM of Two Numbers in Python def gcd(a, b): while b: a, b = b, a % b return a def lcm(a, b): return abs(a * b) // gcd(a, b) num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) print(f"The LCM of {num1} and {num2} is {lcm(num1, num2)}.")
Explanation
- Function Definitions: The
gcd
function finds the greatest common divisor (GCD) of two numbers using the Euclidean algorithm, and thelcm
function calculates the LCM using the formula LCM(a,b)=∣a×b∣GCD(a,b)\text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a, b)}. - Main Program: The program prompts the user to enter two numbers and then calculates the LCM using the
lcm
function and prints the result.
Output
- When you run the above program, it will prompt you to enter two numbers.
- After entering the numbers, it will calculate the LCM and print the result.
Conclusion
- In this tutorial, we learned how to find the LCM of two given numbers using a Python program.
- Understanding this concept is essential for solving various mathematical problems and enhancing your programming skills.