Program to compute gcd of two numbers recursively in Python

Finding the Greatest Common Divisor (GCD) of two numbers is a fundamental mathematical operation. The Euclidean algorithm provides an efficient recursive approach by repeatedly applying the principle that GCD(a, b) = GCD(b, a mod b).

So, if the input is like a = 25, b = 45, then the output will be 5.

Algorithm Steps

To solve this recursively, we will follow these steps −

  • Define a function gcd(). This will take a, b
  • if a is same as b, then
    • return a
  • otherwise when a < b, then
    • return gcd(b, a)
  • otherwise,
    • return gcd(b, a - b)

Example

Let us see the following implementation to get better understanding −

def gcd(a, b):
    if a == b:
        return a
    elif a < b:
        return gcd(b, a)
    else:
        return gcd(b, a - b)

a = 25
b = 45
result = gcd(a, b)
print(f"GCD of {a} and {b} is: {result}")

The output of the above code is −

GCD of 25 and 45 is: 5

How It Works

The algorithm works by recursively reducing the problem size:

  • Base case: When both numbers are equal, that number is the GCD
  • Recursive case: Replace the larger number with the difference of the two numbers
  • This continues until both numbers become equal

Optimized Version Using Modulo

A more efficient approach uses the modulo operator instead of subtraction −

def gcd_optimized(a, b):
    if b == 0:
        return a
    else:
        return gcd_optimized(b, a % b)

a = 25
b = 45
result = gcd_optimized(a, b)
print(f"GCD of {a} and {b} is: {result}")
GCD of 25 and 45 is: 5

Conclusion

The recursive GCD algorithm demonstrates the power of the Euclidean method. The modulo-based version is more efficient as it reduces the number of recursive calls compared to the subtraction-based approach.

Updated on: 2026-03-26T15:40:41+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements