Exercise
Function Multiply & Multiplyrecursive
Objective
Develop a Python program with two functions, Multiply and MultiplyRecursive, to compute the product of two numbers by using addition. The first function should implement an iterative approach, and the second should use recursion.
Example Python Exercise
Show Python Code
# Function to multiply two numbers using iteration (repeated addition)
def Multiply(x, y):
# Initialize result to 0
result = 0
# Add x to result y times
for _ in range(abs(y)):
result += x
# If y is negative, negate the result
if y < 0:
result = -result
return result
# Recursive function to multiply two numbers using addition
def MultiplyRecursive(x, y):
# Base case: if y is 0, the result is 0
if y == 0:
return 0
# Recursive case: add x one time and reduce y
return x + MultiplyRecursive(x, y - 1) if y > 0 else -(x + MultiplyRecursive(x, -y - 1))
# Example usage
x = 5 # First number
y = 3 # Second number
# Call the iterative multiplication function
iterative_result = Multiply(x, y)
print(f"Iterative Multiply({x}, {y}) = {iterative_result}")
# Call the recursive multiplication function
recursive_result = MultiplyRecursive(x, y)
print(f"Recursive Multiply({x}, {y}) = {recursive_result}")
Output
python multiply.py
Iterative Multiply(5, 3) = 15
Recursive Multiply(5, 3) = 15
Share this Python Exercise