Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
How Recursion Works for Multiplication
Multiplication can be thought of as repeated addition. For example, 5 × 3 = 5 + 5 + 5. We can use recursion to break down multiplication into smaller addition problems ?
Example
Below is a demonstration for the same ?
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 = 112
val_2 = 3
print("The computed product is:")
print(compute_product(val_1, val_2))
The computed product is: 336
Step-by-Step Breakdown
Let's trace through how compute_product(5, 3) works ?
def compute_product(val_1, val_2):
print(f"Called with val_1={val_1}, val_2={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
result = compute_product(5, 3)
print(f"Final result: {result}")
Called with val_1=5, val_2=3 Called with val_1=5, val_2=2 Called with val_1=5, val_2=1 Called with val_1=5, val_2=0 Final result: 15
Explanation
- A method named 'compute_product' is defined, that takes two numeric values as parameters.
- If the first value is less than second value, then the function is called again by swapping these parameters.
- If the second value is not 0, the function adds the first value to the result of calling itself with val_2 - 1.
- When val_2 becomes 0, the function returns 0 (base case).
- The recursion effectively computes val_1 × val_2 as val_1 added val_2 times.
Alternative Implementation
Here's a cleaner version without parameter swapping ?
def multiply_recursive(a, b):
# Base case
if b == 0:
return 0
# Handle negative numbers
if b < 0:
return -multiply_recursive(a, -b)
# Recursive case: a * b = a + a * (b-1)
return a + multiply_recursive(a, b - 1)
# Test with different numbers
print(multiply_recursive(7, 4)) # 28
print(multiply_recursive(6, 0)) # 0
print(multiply_recursive(3, -2)) # -6
28 0 -6
Conclusion
Recursive multiplication works by breaking down multiplication into repeated addition. The base case returns 0 when the multiplier reaches 0, and each recursive call adds the multiplicand once while decreasing the multiplier by 1.
