0

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?

1
  • 6
    You recurse in by calling v(n), but you never do anything with what you find. Commented Nov 17, 2013 at 21:43

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, I was originally just returning x directly, but then i realized I needed to re use it for some other methods, so I reset it to 0 and added in the answer variable, but I completely over looked that.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.