To find the greatest common divisor (GCD) of two numbers in Ruby, we can use the built-in method gcd provided by the Math module. Here's an example:
main.rb51 chars5 lines
In the above example, we defined two variables a
and b
with the values 24 and 36, respectively. We then called the gcd
method on a
and passed b
as an argument. The gcd
method returns the greatest common divisor of a
and b
, which is 12 in this case.
We can also define our own recursive method to calculate the GCD using the Euclidean algorithm:
main.rb98 chars9 lines
In this example, we define a method gcd
that takes a
and b
as arguments. If b
is 0, we return a
, indicating that the GCD has been found. Otherwise, we call gcd
with b
and a % b
(the remainder of a
divided by b
). This recursive call repeats until b
becomes 0, at which point the GCD is returned.
gistlibby LogSnag