In this article, we will learn about python program to multiply two numbers using recursion.
Getting Started
The task is to get product of two numbers in python. For example,
If a = 5 and b = 6, then product is 5 x 6 = 30
We have seen 5 different ways to get product of two numbers.
But, in this article, we will do it using recursion.
Program to Multiply Two Numbers using Recursion
Pseudo Algorithm
- Get the smaller number
- Then, call the function recursively smaller number times.
- Terminate the recursive function call when smaller number decreases to 0.
- Basically, we are trying to add bigger number multiple times ( smaller number of times).
### Multiply Two Numbers Using Recursion def product(n1, n2): # If n1 is smaller, swap it with n2. if n1 < n2: return product(n2, n1) # Add n1 to n2 times i.e. n1 + n1 + n1 + ..... n2 times elif n2 != 0: return (n1 + product(n1, n2 - 1)) # If any number is 0, product is 0 else: return 0 print("Result:", product(12, 3))
Output:
Result: 36
That’s how we can write python program to multiply two numbers using recursion.
Reference: Multiplication in Math
Learn about more python examples at – https://tutorialwing.com/python-tutorial/