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

  1. Function Definitions: The gcd function finds the greatest common divisor (GCD) of two numbers using the Euclidean algorithm, and the lcm 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)}.
  2. 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

Python Program to Find the LCM of Two Numbers

  • 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.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *