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.py363 chars14 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.py75 chars4 lines
This will output 60, which is the LCM of the numbers 2, 3, 4, 5, and 6.
gistlibby LogSnag