The Least Common Multiple (LCM) is the smallest positive integer that is a multiple of two or more numbers.
In this article, we will be discussing how to write a Python program to find the LCM of two numbers.
Method 1
One way to find the LCM of two numbers is to use the formula: LCM(a, b) = (a * b) / GCD(a, b)
Where GCD(a, b)
is the Greatest Common Divisor of a and b.
Here is an example of a Python program that uses the above formula to find the LCM of two numbers:
def gcd(a, b):
while b:
a, b = b, a%b
return a
def lcm(a, b):
return (a * b) // gcd(a, b)
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("LCM of", num1, "and", num2, "is: ", lcm(num1, num2))
In this program, we have first created the gdc()
function that returns the Greatest Common Divisor of two number a and b, and then we have our lcm()
function that takes in two arguments, a and b, and returns the LCM of the two numbers. The user is prompted to enter the two numbers, and the LCM is calculated and printed to the console.Method 2: Using the math module
The math module is a built-in Python module that provides mathematical functions and constants. We will be using the gcd()
function from the math module to find the greatest common divisor of two or more numbers.
Once the math module is imported, we can define a function that takes in two or more numbers as arguments and returns the LCM. The basic algorithm for finding the LCM of two or more numbers is to first find the greatest common divisor of the numbers using the gcd()
function and then divide the product of the numbers by the greatest common divisor.
Here is an example of a Python program that finds the LCM of two numbers:
import math
def lcm(a, b):
return (a*b)//math.gcd(a, b)
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The LCM of", num1, "and", num2, "is", lcm(num1, num2))
In this program, the lcm()
function takes in two arguments, a and b, and returns the LCM of the two numbers. The user is prompted to enter the two numbers, and the LCM is calculated and printed to the console.
Finding LCM of more than two number
To find the LCM of more than two numbers, we can use the reduce()
function from the functools module.
The reduce()
function applies a given function to the elements of an iterable, and returns a single value. We can use this function to repeatedly find the LCM of two numbers until all numbers have been processed.
Here is an example of a Python program that finds the LCM of three numbers:
from functools import reduce
import math
def lcm(a, b):
return (a*b)//math.gcd(a, b)
nums = [int(x) for x in input("Enter three numbers separated by space: ").split()]
print("The LCM of", nums, "is", reduce(lcm, nums))
In this program, the user is prompted to enter three numbers separated by spaces, and the LCM is calculated and printed to the console.