In: Computer Science
Implement a recursive algorithm to compute the product of two integers (in java). Your algorithm can only perform addition and subtraction; no multiplication. Analyze the running time and space complexity of your solution.
please find below java program for multiplication using recursion
public class Main
{
public static void main(String[] args) {
System.out.println("Product: "+multiplication(2,3,0));
}
public static int multiplication(int n,int m,int result){
if(n==0)
{
return result;
}
else
{
return multiplication(n-1,m,result+m);
}
}
}
Time Analysis
multiplication(0,m,result) is only comparison
multiplication(n,m,result)=is 1 comparison,1 subtraction,1 addition
so T(n)=T(n-1)+3
T(0)=1
T(n) = T(n-1) + 3
= T(n-2) + 6
= T(n-3) + 9
= T(n-4) + 12
= ...
= T(n-k) + 3k
as we know T(0) = 1
we need to find the value of k for which n - k = 0, k = n
T(n) = T(0) + 3n , k = n
= 1 + 3n
that gives us a time complexity of O(n)
Space complexity
For every call to the recursive function, the state is saved onto the call stack, till the value is computed and returned to the called function.
The space complexity of recursive multiplication implementation is O(n)