The Least Common Multiple (LCM) of two or more integers is the smallest positive integer that is divisible by each of the numbers without leaving a remainder. For example, the LCM of 3, 5, and 7 is 105, because 105 is the smallest number that is divisible by all three.
In this post, I will provide a Python code to find the LCM of a given set of numbers. The code uses the following formula to iteratively compute the LCM:
where GCD stands for Greatest Common Divisor.
The program uses Python’s math.gcd() function to compute the GCD of two numbers. The GCD is the largest number that divides both numbers without leaving a remainder. For example, math.gcd(12, 18) returns 6.
Here is the Python code:
import sys
import math
def find_lcm(numbers):
"""
Function to find the LCM of a list of numbers.
"""
lcm = 1
for number in numbers:
lcm = lcm * number // math.gcd(lcm, number)
return lcm
def main():
"""
Find LCM of given numbers. provide comma-separated numbers from command-line
"""
# provide the numbers as a command-line argument
args = sys.argv
# check if user provided a value or not
if len(args) < 2:
print("please provide numbers as command-line argument")
else:
numbers = list(map(int, args[1].split(",")))
print(f"The LCM of {numbers}: {find_lcm(numbers)}")
if __name__ == "__main__":
main()
To execute this code, save it as find_lcm.py (or any name you prefer) and provide all the numbers from the command line as comma-separated values, as shown below.
python find_lcm.py 12,15,20
If you encounter any issues with the code, please leave comments.