Recursive multiplication in Python

Problem

Write a Python recursive function to compute the product of two positive integers.

Solution

The product of two positive integers (A*B) is nothing but the sum of the first integer (A), (B) times

Code

Here is the code in Python

//Includes
def RecursiveProduct(a, b):

	# Base case 1
	if a == 0 or b == 0:
		return 0
	
	# Base case 2
	if b == 1:
		return a
	
	return a + RecursiveProduct(a, b-1)

print "3 x 4 = {}".format(RecursiveProduct(3, 4))

If you think about the code above, it is not recursive naturally but iterative. What we are doing actually is performing iteration using recursion which is a weird way to do it. Questions ? use the comments section below.

Leave a Reply