Editor

Least Common Multiple of a List

#272 · Math · Intermediate · 60 XP · about 10 min

Several bus routes all leave the depot together at 6:00, and route i leaves again every nums[i] minutes. The next time they all leave together is the least common multiple (LCM) of the intervals: the smallest positive number that every interval divides.

Write lcm_of_list(nums) that returns the least common multiple of a list of positive integers.

Examples

lcm_of_list([4, 6])          # returns 12
lcm_of_list([2, 3, 4, 5])    # returns 60
lcm_of_list([4, 6, 8])       # returns 24

Buses every 4 and every 6 minutes meet again after 12 minutes: 12 is the first number in both 4, 8, 12 and 6, 12. For [4, 6, 8], multiplying everything (192) gives a common multiple, but not the least one.

Constraints

  • 1 <= len(nums) <= 3,000
  • 1 <= nums[i] <= 10^6
  • The answer can have thousands of digits; Python's integers have no size limit, so return it exactly.

Note

Python 3.9 added math.lcm, which does all of this in one call. Try building it from a GCD instead: the idea is what matters here.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.