Greatest Common Divisor Recursively
Have you ever had to divide a large batch of items into equal groups? Finding the Greatest Common Divisor (GCD) is exactly that—it is the largest possible number that divides two integers without leaving any remainder.
Imagine you have 48 blue marbles and 18 red marbles. If you want to put them into bags where every bag has the same number of marbles and there are no marbles left over, the largest number of marbles per bag would be 6. That is the power of the GCD.
Instead of trying every possible divisor, we can use a clever mathematical trick called the Euclidean algorithm. The idea is that the GCD of two numbers also divides their difference, or more simply, gcd(a, b) is the same as gcd(b, a MOD b). We just keep repeating this until one number hits zero, and the remaining number is our answer.
Example Input & Output
7 divides both numbers exactly.
These numbers share no common divisor larger than 1.
The largest integer that divides both 48 and 18 is 6.
Algorithm Flow

Solution Approach
The Euclidean algorithm is a classic example of recursion because the solution to a large problem depends on the solution to a slightly smaller version of the same problem.
To build this in pseudocode, we start with a base case: if the second number b is 0, we stop and return a. That is our answer. If b is not zero, we simply call the function again, but this time we pass b as the first argument and the remainder of a divided by b as the second.
By using MOD, the numbers shrink incredibly fast. For example, computing gcd(48, 18) only takes a few steps: it goes to gcd(18, 12), then gcd(12, 6), and finally gcd(6, 0). It is efficient, elegant, and much faster than counting one by one.
Best Answers
function gcd(a: integer, b: integer) -> integer
dictionary
algorithm
if b = 0 then
return a
else
return gcd(b, a MOD b)
endif
endfunction
program greatest_common_divisor_recursive
dictionary
a, b: integer
algorithm
input(a, b)
output(gcd(a, b))
endprogramComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
