Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I know that, in Ruby, you can use the Integer#lcm 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
like image 320
Kerrick Avatar asked May 28 '12 11:05

Kerrick


2 Answers

Any operation that takes two operands can be applied iteratively to a collection by folding it: Enumerable#inject/reduce. To cover the empty case, pass as first argument the identity element of the operation, which is 1 for the least common denominator.

[5, 3, 10, 2, 20].reduce(1) { |acc, n| acc.lcm(n) } # => 60

Which can be also written as:

[5, 3, 10, 2, 20].reduce(1, :lcm)
like image 171
tokland Avatar answered Sep 25 '22 05:09

tokland


In addition to tokland's answer, if you really want an #lcm method to act on an array of integers, you could add an instance method to the Array class.

class Array
  def lcm
    self.reduce(1, :lcm)
  end
end

puts 10.lcm(15)
# => 30
puts [5,3,10,2,20].lcm
# => 60

(This practice is called Monkey patching, as you're extending a class at runtime. Some people do frown upon the practice though.)

like image 43
Jochem Schulenklopper Avatar answered Sep 25 '22 05:09

Jochem Schulenklopper