Recursive Multiplication Python
Recursive Multiplication Python
In this tutorial, we will learn how to write a Python program to get the multiplication of two numbers using the recursive approach.
In the recursive multiplication approach, we will use the following steps for writing the program:
Step 1: We will take two integers as user input and store them in two different variables, i.e., num1 & num2.
Step 2: If num1 is less than num2, we will swap two variables inside the function. We will also compare the values inside the function.
Step 3: We will find the num2 times sum of the num1 variable using the recursion method.
Step 4: If any of the variables become zero, the function will return 0 in output.
Step 5: Print the result of multiplication in the output of the program.
Let's understand the implementation of above steps through the following Python program:
Example –
# Define a default recursive multiplication function def RecurMulti (m, n): if m < n: # checking which number is greater return RecurMulti (n, m) # swapping numbers elif n != 0: # if number is not 0 return (m + RecurMulti (m, n - 1)) # recursive multiplication else: return 0 # returning 0 in every other case # Taking both numbers as input from user num1 = int (input ("Enter the first positive number :")) num2 = int (input ("Enter the second positive number :")) # Storing the result of Multiplication of both number Product_Result = RecurMulti (num1, num2) # Printing result in output print ("The result of multiplication of two number is: ", Product_Result)
Output:
Enter the first positive number : 5 Enter the second positive number : 32 The result of the multiplication of two number is: 160
We can use this recursive approach in our Python program to find the product of any two positive numbers given by the user.