Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 48 / 68

Finding the GCD and LCM

In this lesson you will learn to find the greatest common divisor and least common multiple with Ruby's built-in gcd and lcm methods. This is for anyone searching for "Ruby gcd lcm how to use".

Ruby provides .gcd (greatest common divisor) and .lcm (least common multiple) as integer methods out of the box. Internally they use the Euclidean algorithm, which dates back to antiquity.

The sample code finds the GCD with 12.gcd(18) and the LCM with 4.lcm(6), each in a single method call. Notice how the whole thing is handled by the standard library, with no algorithm to implement yourself.

A common stumbling block for beginners is wondering why this is so easy. Using the built-in method is faster and safer than writing your own, and it is a good illustration of how complete Ruby's standard library is. Implementing it yourself is still worthwhile practice if you want to understand the mechanism.

For three or more numbers, combining it with reduce does the job. It is a good demonstration of how much the standard library covers, even for mathematical work.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)