Recursive Multiplication in Python

Recursive Multiplication in Python

Fumbani Banda Oct-22, 2021 Oct-19, 2021 Python Python Math

This tutorial will introduce integer multiplication with recursion in Python.

Recursion is a technique that uses a function that calls itself one or more times until a base condition is met, at which time the rest of the repetition is processed from the last one called to the first. Recursion is widely used in programming to solve complex problems where the solution depends on the solutions to smaller instances of the same problem.

Recursive Multiplication in Python

Multiplication of a number is repeated addition. Recursive multiplication would repeatedly add the larger number of the two numbers, (x,y) to itself until we get the required product.

Assume that x >= y. Then we can recursively add x to itself y times. In this case, you recursively add 3 to itself twice.

def multiply(x,y):
    if  y == 0 :
        return 0
    elif y < 0:
        return -(x - multiply(x,y+1))
        return x + multiply(x,y-1)

if __name__ == '__main__':
    print("3 * 2 = " ,multiply(3,2))
    print("3 * (-2) = ",multiply(3,-2))
    print("(-3) * 2 = ",multiply(-3,2))
    print("(-3) * (-2)= ",multiply(-3,-2))


3 * 2 =  6
3 * (-2) =  -6
(-3) * 2 =  -6
(-3) * (-2)=  6
Fumbani Banda avatar Fumbani Banda avatar

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

LinkedIn GitHub

Related Article - Python Math

  • Calculate Factorial in Python
  • Calculate Inverse of Cosine in Python
  • Calculate Modular Multiplicative Inverse in Python
  • Fit Poisson Distribution to Different Datasets in Python
  • Reduce Fractions in Python
  • Define an Infinite Value in Python