Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to compute GCD - Python Program

Example 1 :

def gcd(a, b): """Return GCD using recursion.""" if b == 0: return a return gcd(b, a % b) print(gcd(48, 18))

Output

 
OUTPUT 1 :
6
 

Example 2 :

def gcd_recursive(a, b): """ Computes the Greatest Common Divisor (GCD) of two non-negative integers using the recursive Euclidean algorithm. Args: a: The first non-negative integer. b: The second non-negative integer. Returns: The GCD of a and b. """ if b == 0: return a else: return gcd_recursive(b, a % b) # Example Usage num1 = int(input("Enter a number : ")) num2 = int(input("Enter a number : ")) result = gcd_recursive(num1, num2) print(f"The GCD of {num1} and {num2} is: {result}")

Output

 
OUTPUT 1 :
Enter a number  : 48
Enter a number  : 18
The GCD of 48 and 18 is: 6