Search⌘ K

Solution Review: Product of Two Positive Integers

Explore the recursive method to multiply two positive integers by summing one integer repeatedly. Understand the implementation details, address recursion depth errors, and optimize recursive calls by swapping parameters for efficiency. This lesson prepares you to handle recursion challenges in Python.

We'll cover the following...

Let’s discuss the solution to the challenge in the previous lesson. The problem was to find the product of two positive integers.

Implementation

Let’s have a look at the implementation below:

Python 3.5
def recursive_multiply(x, y):
# This cuts down on the total number of
# recursive calls:
if x < y:
return recursive_multiply(y, x)
if y == 0:
return 0
return x + recursive_multiply(x, y-1)
x = 500
y = 2000
print(x * y)
print(recursive_multiply(x, y))

Explanation

The hint indicated the following:

5 * 3 = 5 + 5 + 5 = 15

We make use of the hint in the implementation. Let’s skip the code on ...