Python Program to Find the Product of two Numbers Using Recursion


When it is required to find the product of two numbers using recursion technique, a simple if condition and recursion is used.

The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.

Example

Below is a demonstration for the same −

 Live Demo

def compute_product(val_1,val_2):
   if(val_1<val_2):
      return compute_product(val_2,val_1)
   elif(val_2!=0):
      return(val_1+compute_product(val_1,val_2-1))
   else:
      return 0
val_1 = int(input("Enter the first number... "))
val_2 = int(input("Enter the second number... "))
print("The computed product is: ")
print(compute_product(val_1,val_2))

Output

Enter the first number... 112
Enter the second number... 3
The computed product is:
336

Explanation

  • A method named ‘compute_product’ is defined, that takes two numeric values as paramters.
  • If the first value is less than second value, then the function is called again by swapping these parameters.
  • If the second value is 0, the function is called by passing first value, and subtracting ‘1’ from second value, and adding the first value to the result of the function.
  • Otherwise the function returns 0.
  • Outside the function, two numbers value are entered by the user.
  • The method is called by passing these two values.
  • The output is displayed on the console.

Updated on: 12-Mar-2021

410 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements