To find the greatest common divisor of a list of numbers in Ruby, we can use the gcd
method provided by the Integer
class. We can apply this method to pairs of numbers and reduce the list to a single value.
main.rb62 chars4 lines
Here, numbers.reduce
applies the block passed to it to each consecutive pair of numbers in the list, using the first number as an initial value. a.gcd(b)
finds the greatest common divisor of the two numbers, and this result is used as the next value of a
, until a single value is obtained.
We can test this function with an array of numbers:
main.rb57 chars3 lines
In this example, the greatest common divisor of 12, 24, 36, and 48 is 12.
gistlibby LogSnag