Reputation: 69
The method is for a calculator and is supposed to return log2(n). All of the methods used (monus which is minus spelled wrong) power, ect) are written correctly. s(n) just adds one to n and p(n) subtracts one.
when I call the method in the main it gets the remainder right, but always returns 0 for the answer. this confuses me. I am sure it has to do with the fact that i am reinitializing answer to 0 each time the method is called but shouldn't that not matter because it is always going to get set to x before it returns anything?
x is a private static variable that has been set to 0 outside of the method.
public static long v(long n)
{
long answer =0;
if (power(2,x) > n)
{
x = p(x);
setRemainder(monus(n,power(2,x)));
answer = x;
}
else if(power(2,x) ==n)
{
setRemainder(0);
answer = x;
}
else
{
x = s(x);
v(n);
}
x=0;// reset x so it can be used again.
return answer;
}
can anyone help me?
Upvotes: 0
Views: 101
Reputation: 10959
As stated in the comments you make the recursive call in the else
statement but don't assign this to anything when the recursive call returns.
Consider this:
On your first call: x = 0
so probably going to the else statement and enter the recursion. At some point of recursion one of your conditional statements will be true and in this case answer
is returned but not assigned in the way back down the stack of recursive calls.
So would look like this:
1: v(n) // this calls v(n) again
2: v(n) returns answer = x // this returns an answer
1: returns answer = 0 // now the return falls down a level to where the recursive
// call was and the answer is lost as was not assigned
Upvotes: 0
Reputation: 724
You should change the line:
v(n);
to:
answer = v(n);
Right now, if the last else block is executed, the answer variable is not changed - so it's still 0.
Upvotes: 1