Code Logo

Greatest Common Divisor Recursively

Published at19 Apr 2026
Medium 0 views
Like0

This problem is about finding the largest positive integer that divides two numbers exactly. That value is called the greatest common divisor, or GCD.

For example, the GCD of 48 and 18 is 6 because 6 divides both numbers and no larger common divisor exists. The GCD of 21 and 14 is 7.

A very efficient recursive method for this problem is the Euclidean algorithm. It uses the idea that:

gcd(a, b) = gcd(b, a MOD b)

This keeps reducing the second value until it becomes 0. When that happens, the first value is the answer.

So the task is to read two integers, apply the recursive Euclidean algorithm, and print the GCD.

Example Input & Output

Example 1
Input
a = 21, b = 14
Output
7
Explanation

7 divides both numbers exactly.

Example 2
Input
a = 9, b = 28
Output
1
Explanation

These numbers share no common divisor larger than 1.

Example 3
Input
a = 48, b = 18
Output
6
Explanation

The largest integer that divides both 48 and 18 is 6.

Algorithm Flow

Recommendation Algorithm Flow for Greatest Common Divisor Recursively
Recommendation Algorithm Flow for Greatest Common Divisor Recursively

Solution Approach

The key to this problem is choosing the right recursive rule.

If the second number b is 0, then the recursion stops and the answer is simply a. This is the base case.

If b is not 0, then replace the pair (a, b) with (b, a MOD b) and solve the smaller problem recursively:

return gcd(b, a MOD b)

For example, to compute gcd(48, 18):

gcd(48, 18) -> gcd(18, 12) gcd(18, 12) -> gcd(12, 6) gcd(12, 6) -> gcd(6, 0)

At that point the answer is 6.

This method is much better than checking every divisor one by one. The numbers shrink quickly, so the recursive solution is efficient and elegant.

The full algorithm is: read a and b, call a recursive function such as gcd(a, b), and print the result.

Best Answers

Solutions Coming Soon

Verified best solutions for this Challenge are still being analyzed and will be available soon.