Ruby Coding Interview Question: Find the Greatest Common Divisor (GCD) of Two Numbers
Solution
def gcd(a, b)
b == 0 ? a : gcd(b, a % b)
end
puts gcd(24, 36) #=> 12
Let’s break down the code and understand how it works:
- The
gcd
method takes two parameters,a
andb
, representing the two numbers for which you want to find the GCD. - In this implementation, the code uses a ternary operator
b == 0 ? a : gcd(b, a % b)
to determine the base case for the recursion. Ifb
is equal to 0, it means we have found the GCD, so the method simply returnsa
. Otherwise, it makes a recursive call togcd
with the argumentsb
anda % b
. This step is equivalent to swapping the values ofa
andb
in the iterative implementation. - The expression
a % b
calculates the remainder whena
is divided byb
. By repeatedly dividing the larger number by the smaller number and taking the remainder, we ensure that in each iteration,a
becomes the smaller number andb
becomes the remainder. - The recursive calls continue until
b
becomes 0, at which point the base case is triggered, and the GCD, which is stored ina
, is returned as the final result.
To test the code, you provided an example usage:
puts gcd(24, 36) #=> 12