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.
Examples:
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:
C++
<?php
function multrecur( $n , $m )
{
if ( $n > 0 && $m < 0)
{
return multrecur( $m , $n );
}
else if ( $n < 0 && $m < 0)
{
return multrecur((-1 * $n ),
(-1 * $m ));
}
if ( $n > $m )
{
return multrecur( $m , $n );
}
else if ( $m != 0)
{
return $n + multrecur( $n , $m - 1);
}
else
{
return 0;
}
}
echo "5 * 3 = " . multrecur(5, 3) . "\n" ;
echo "5 * (-3) = " . multrecur(5, -3) . "\n" ;
echo "(-5) * 3 = " . multrecur(-5, 3) . "\n" ;
echo "(-5) * (-3) = " . multrecur(-5, -3) . "\n" ;
?>
|
Javascript
<script>
function multrecur(n, m)
{
if (n > 0 && m < 0)
{
return multrecur(m, n);
}
else if (n < 0 && m < 0)
{
return multrecur((-1 * n), (-1 * m));
}
if (n > m)
{
return multrecur(m, n);
}
else if (m != 0)
{
return n + multrecur(n, m - 1);
}
else
{
return 0;
}
}
document.write( "5 * 3 = " + multrecur(5, 3) + "<br>" );
document.write( "5 * (-3) = " + multrecur(5, -3) + "<br>" );
document.write( "(-5) * 3 = " + multrecur(-5, 3) + "<br>" );
document.write( "(-5) * (-3) = " + multrecur(-5, -3) + "<br>" );
</script>
|
Output:
5 * 3 = 15
5 * (-3) = -15
(-5) * 3 = -15
(-5) * (-3) = 15
Time Complexity: O(max(N, M)) Auxiliary Space: O(max(N, M))
|