Kerrick Kerrick - 5 months ago 16
Ruby Question

Getting the least common multiple of an array of integers in Ruby

I know that, in Ruby, you can use the

method to get the least common multiple of two numbers. For example:

10.lcm(15)
# => 30


Is there an efficient (or built-in to the core or stdlib) way to get the least common multiple of all the integers in a given array? For example:

[5, 3, 10, 2, 20].lcm
# => 60

Answer
>> [5, 3, 10, 2, 20].reduce(:lcm)
=> 60 

Any operation taking 2 operands can be applied iteratively to a collection folding it, Enumerable#reduce in Ruby.

Comments