Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 195 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting the least common multiple of an array of integers in Ruby

#1
I know that, in Ruby, you can use the [`Integer#lcm`](

[To see links please register here]

) 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
Reply

#2
[5,3,10,2,20].reduce(&:lcm)
Reply

#3
Any operation that takes two operands can be applied iteratively to a collection by [folding][1] it: [Enumerable#inject/reduce][2]. To cover the empty case, pass as first argument the [identity element][3] 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)


[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

Reply

#4
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.

```lang-ruby
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][1], as you're extending a class at runtime. Some people do frown upon the practice though.)

[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through