To find the least common multiple of two numbers, the easiest way is to use the equation that the product of two numbers equals the least common multiple times the greatest common divisor.
def gcd(a,b):
if b == 0:
return a
return gcd(b, a % b)
def lcm(x, y):
return x * y / gcd(x, y)
print(lcm(20,37))
print(lcm(4,6))
#Output:
740.0
12.0
You can also use a loop which will brute force the least common multiple of two or more numbers.
def lcm(lst):
lcm_temp = max(lst)
while(True):
if all(lcm_temp % x == 0 for x in lst):
break
lcm_temp = lcm_temp + 1
return lcm_temp
print(lcm([20,37]))
print(lcm([4,6]))
print(lcm([20,16,28]))
print(lcm([6,8,10,12]))
#Output:
740
12
560
120
Python allows us to implement complex algorithms to do various calculations. One such calculation is finding the least common multiple of two numbers
The least common multiple of two integers a and b is the smallest positive integer that is divisible by both.
To find the least common multiple of two numbers, the easiest way is to use the mathematical identity that states that the product of two numbers is equal to the product of the greatest common divisor (GCD) and the least common multiple (LCM).
Therefore, we can get the GCD of two numbers with the Euclidean Algorithm and then just divide to get the least common multiple.
Below is a function which will calculate the least common multiple of two integers in Python.
def gcd(a,b):
if b == 0:
return a
return gcd(b, a % b)
def lcm(x, y):
return x * y / gcd(x, y)
print(lcm(20,37))
print(lcm(4,6))
#Output:
740.0
12.0
How to Calculate the LCM of Multiple Numbers in Python
If you want to calculate the LCM of more than two numbers, you can use a brute force method which will loop until you’ve found a number which each number can divide evenly.
First, we take the max of a list of integers to get the starting point.
Then, we loop until we find a number that each element in the list of numbers divides evenly.
When we find a number which is divisible by all of the numbers in the list, we have found our least common multiple.
Below is the function which will find the least common multiple given a list of integers in Python.
def lcm(lst):
lcm_temp = max(lst)
while(True):
if all(lcm_temp % x == 0 for x in lst):
break
lcm_temp = lcm_temp + 1
return lcm_temp
print(lcm([20,37]))
print(lcm([4,6]))
print(lcm([20,16,28]))
#Output:
740
12
560
Hopefully this article has been useful for you to learn how to get the least common multiple of two or more numbers using Python.