Given two numbers N and M. The task is to find the product of the 2 numbers using recursion.
Note: The numbers can be both positive or negative.
Input : N = 5 , M = 3 Output : 15 Input : N = 5 , M = -3 Output : -15 Input : N = -5 , M = 3 Output : -15 Input : N = -5 , M = -3 Output:15
A recursive solution to the above problem for only positive numbers is already discussed in the previous article. In this post, a recursive solution for finding the product for both positive and negative numbers is discussed.
Below is the step by step approach:
- Check if one or both of the numbers are negative.
- If the number passed in the second parameter is negative swap the parameters and call the function again.
- If both of the parameters are negative call the function again and pass the absolute values of the numbers as parameters.
- If n>m call the function with swapped parameters for less execution time of the function.
- As long as m is not 0 keep on calling the function with subcase n, m-1 and return n + multrecur(n, m-1).
Below is the implementation of the above approach:
5 * 3 = 15 5 * (-3) = -15 (-5) * 3 = -15 (-5) * (-3) = 15
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Product of 2 Numbers using Recursion
- Print numbers 1 to N using Indirect recursion
- Sum of natural numbers using recursion
- Print even and odd numbers in a given range using recursion
- Decimal to Binary using recursion and without using power operator
- Count Set-bits of number using Recursion
- Sum of N-terms of geometric progression for larger values of N | Set 2 (Using recursion)
- Numbers less than N which are product of exactly two distinct prime numbers
- Program for dot product and cross product of two vectors
- Reverse a stack using recursion
- Remove duplicates from a sorted linked list using recursion
- Reverse a Doubly linked list using recursion
- Decimal to binary number using recursion
- Sum of digit of a number using recursion
- Binary to Gray code using recursion
- Delete a linked list using recursion
- Program for length of a string using recursion
- Print alternate nodes of a linked list using recursion
- Reversing a queue using recursion
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.