find the least common multiple of a list of numbers in python

To find the least common multiple (LCM) of a list of numbers in Python, we can use the math module's lcm function. Here's a custom function that takes a list of numbers as input and returns their LCM:

main.py
import math

def lcm_list(numbers):
    """
    Returns the least common multiple of a list of numbers.
    """
    # Set lcm to the first number
    lcm = numbers[0]
    # Loop through the numbers in the list
    for n in numbers[1:]:
        # Calculate the LCM of the current number and the current lcm
        lcm = lcm * n // math.gcd(lcm, n)
    return lcm
363 chars
14 lines

Here, we set lcm to the first number in the list, then loop through the remaining numbers in the list. For each number, we calculate the LCM of that number and the current value of lcm using the math.lcm function. We store the result back in lcm and continue until we've processed every number in the list.

Note that we use integer division (//) to ensure that our code works correctly with Python 3's integer division behavior.

We can call this function with a list of numbers like this:

main.py
numbers = [2, 3, 4, 5, 6]
lcm = lcm_list(numbers)
print(lcm)  # Output: 60
75 chars
4 lines

This will output 60, which is the LCM of the numbers 2, 3, 4, 5, and 6.

related categories

gistlibby LogSnag