Python Code Example: greatest common divisor (recursive)

The code calculates the greatest common divisor (GCD) of two integers a and b using the Euclidean algorithm. The gcd function is a recursive function that returns the GCD of two numbers by subtracting the smaller number from the larger number until one of them is zero. The GCD of the two numbers is then returned.

In the main part of the code, two numbers a and b are initialized to 200 and 60, respectively. The GCD of a and b is then calculated and printed using the gcd function. The result will be “Greatest common divisor is: 20”.

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


a, b = 200, 60

print("Greatest common divisor is: " + str(gcd(a, b)))
Output
Greatest common divisor is: 20