In: Computer Science
static int product(int x,int y){
if(x==0||y==0){//checking if x or y is 0
return 0;//if x or y is 0, then the return value and x*y will be zero.
}else if(y<0&&x<0){
x=-x;//Changing the sign of x
y=-y;//Changing the sign of y
}else if(x>=1){
return (y+product(x-1,y));
}
return (x+product(x,y-1));
}
find the space complexity and the time complexity of the above algorithm.
Time Complexity
Let the function T(x,y) denotes the number of operations perform by calling the product function:-
---------------------------------------------------------------------------------
Space Complexity - The space complexity is determined by the depth of recursion tree i.e the number of return statements as every recursive call is stored in system stack.