Ruby Coding Interview Question: Find the Greatest Common Divisor (GCD) of Two Numbers

Gokul
4 min readJun 8, 2023

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 and b, 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. If b is equal to 0, it means we have found the GCD, so the method simply returns a. Otherwise, it makes a recursive call to gcd with the arguments b and a % b. This step is equivalent to swapping the values of a and b in the iterative implementation.
  • The expression a % b calculates the remainder when a is divided by b. 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 and b 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 in a, is returned as the final result.

To test the code, you provided an example usage:

puts gcd(24, 36) #=> 12

--

--