To get the greatest common divisor and least common multiple of the integers ʻa`and`

b` in Ruby, Integer # gcd, respectively. /i/gcd.html), Integer # lcm

```
#Greatest common divisor (GCD: Greatest Common Divisor）
a.gcd(b)
#Least common multiple (LCM: Least Common Multiplier）
a.lcm(b)
```

To do.

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 divisors and least common multiples 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)
```

Obtained at. The same applies to the least common multiple,

```
a.lcm(b).lcm(c)
```

Obtained at.

So what if a set of integers was given as an array? You can write as follows.

```
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 to give a symbol without giving a block.

Recommended Posts