find the greatest common divisor of two numbers in ruby

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.rb
a = 24
b = 36
gcd = a.gcd(b)
puts gcd # Output: 12
51 chars
5 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.rb
def gcd(a, b)
  return a if b == 0
  gcd(b, a % b)
end

a = 24
b = 36
puts gcd(a, b) # Output: 12
98 chars
9 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