find the greatest common divisor of a list of numbers in ruby

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.rb
def list_gcd(numbers)
  numbers.reduce { |a,b| a.gcd(b) }
end
62 chars
4 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.rb
numbers = [12, 24, 36, 48]
puts list_gcd(numbers) #=> 12
57 chars
3 lines

In this example, the greatest common divisor of 12, 24, 36, and 48 is 12.

related categories

gistlibby LogSnag