In this tutorial, we will learn how to find the Least Common Multiple (LCM) of two numbers in Python. We will cover the basic concept of LCM and implement functions to perform the calculation using both the built-in math library and a regular method.
The Least Common Multiple (LCM) of two or more integers is the smallest positive integer that is divisible by each of the integers. For example, the LCM of 4 and 5 is 20.
The syntax to find the LCM of two numbers in Python can be done in two ways:
import math
def find_lcm_math(a, b):
return abs(a * b) // math.gcd(a, b)
def find_lcm_regular(a, b):
greater = max(a, b)
while True:
if greater % a == 0 and greater % b == 0:
return greater
greater += 1
We can use the built-in math library in Python to find the LCM of two numbers.
For example,
math
module.find_lcm_math
that takes two parameters a
and b
.abs(a * b) // math.gcd(a, b)
.import math
def find_lcm_math(a, b):
return abs(a * b) // math.gcd(a, b)
# Find the LCM of 4 and 5 using the math library
result = find_lcm_math(4, 5)
# Print the result
print('LCM of 4 and 5 using math library is', result)
LCM of 4 and 5 using math library is 20
We can use a regular method to find the LCM of two numbers by iterating through multiples.
For example,
find_lcm_regular
that takes two parameters a
and b
.while
loop to find the first number that is divisible by both a
and b
.def find_lcm_regular(a, b):
greater = max(a, b)
while True:
if greater % a == 0 and greater % b == 0:
return greater
greater += 1
# Find the LCM of 4 and 5 using the regular method
result = find_lcm_regular(4, 5)
# Print the result
print('LCM of 4 and 5 using regular method is', result)
LCM of 4 and 5 using regular method is 20