[Ruby] Find the greatest common divisor and least common multiple of arbitrary integers in Ruby

less than 1 minute read

To get the greatest common divisor and least common multiple of the integers a and b in Ruby, use Integer#gcd,Integer#lcm

# Greatest common divisor (GCD)
a.gcd(b)

# LCM (Least Common Multiplier)
a.lcm(b)

Like

For example, the greatest common divisor and least common multiple of 4 and 6 are

puts 4.gcd(6) # => 2
puts 4.lcm(6) # => 12

And so on.

Then, what are the greatest common divisor and least common multiple of the three integers a, b, and c? Since the greatest common divisor of $a$, $b$, and $c$ is “the greatest common divisor of $a$ and $b$” and the greatest common divisor of $c$,

a.gcd(b).gcd(c)

Can be obtained at. The same applies to the least common multiple,

a.lcm(b).lcm(c)

Can be obtained at.

Then what if the set of integers was given as an array? You can write it like this:

numbers = [30, 20, 15]

# Greatest common divisor
puts numbers.inject(:gcd) # => 5

# Least common multiple
puts numbers.inject(:lcm) # => 60

Enumerable#inject had a usage of giving symbols without giving blocks.