I am using a recursive method to calculate, and in-order to track the result, I am using, a global static variable to store the result. Although, my code is incorrect, as while considering base case. According to my code, power(2,3) should return 4. If I check using dry run method. But actually, the value of ans variable, changes only once in the whole execution. My question is, that why is the value of ans not getting updated, and for any value of power n , and base being 2. My answer is always returned as base value itself. Can anyone debug my code and help me understand the behavior of global static variable inside recursive method call
public class Solution {
static int ans=1;
public static int power(int x, int n) {
/* Your class should be named Solution
* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
if(n==0)
return 1;
if(n==1)
return x;
else
ans=ans*power(x,n-1);
return ans;
}
}
The code doesn't work correctly because of order-of-evaluation.
Say you call power(3, 4)
.
ans = 1
power(3, 4):
ans=ans*power(x,n-1) -> 1*power(3,4-1)
power(3, 3):
ans=ans*power(x,n-1) -> 1*power(3,3-1)
power(3, 2):
ans=ans*power(x,n-1) -> 1*power(3,2-1)
power(3, 1):
return 3
ans=1*power(3,2-1) =1*3 =3
return ans -> return 3
ans=1*power(3,3-1) =1*3 =3
return ans -> return 3
ans=1*power(3,4-1) =1*3 =3
return ans -> return 3
Result is:
ans = 3
return 3
That is because, when you write ans=ans*power(x,n-1)
, the value of ans
is evaluated before the power()
method is invoked.
Now, if you had written ans=power(x,n-1)*ans
instead, the code would flow like this instead:.
ans = 1
power(3, 4):
ans=power(x,n-1)*ans -> power(3,4-1)
power(3, 3):
ans=power(x,n-1)*ans -> power(3,3-1)
power(3, 2):
ans=power(x,n-1)*ans -> power(3,2-1)
power(3, 1):
return 3
ans=power(3,2-1)*ans =3*1 =3
return ans -> return 3
ans=power(3,3-1)*ans =3*3 =9
return ans -> return 9
ans=power(3,4-1)*ans =9*9 =81
return ans -> return 81
Result is:
ans = 81
return 81
Which is also wrong.
Basically, you should not use fields in a recursive method, except for values that don't change during recursion, or potentially for a result collector.