简体   繁体   中英

Need understanding of this recursion

I dont know why but I cant trace this recursion for the death of me and its really pissing me off. I would love if somebody could help explain how to go through this.

public class MindNumber
{

  public static int numb(int i)
  {
    int result;


    if (i < 1)
    {
      result = -1;  

    }
    else if (i < 10)
    {
      result = numb(i - 1) + numb(i - 2);

    }
    else if (i % 2 == 0)
    {
      result = numb(i / 2);
    }
    else
    {
      result = numb(i / 2) + numb(i % 2);

    }

    return result;
  }
}

public class MindNumberDriver
{
  public static void main(String[] args)
  {
    int i;

    i = MindNumber.numb(12);

    System.out.println(i);

  }
}

The output is -21. Don't understand how it gets to this honestly.

This is the negative Fibonacci sequence for numbers in the range 1 through 9:

-1, -1, -2, -3, -5, -8, -13, -21, -34, ...
f(6) = 21

The critical steps here are the first two conditional clauses, i < 1 and i < 10. The other two translate simply:

If **i** is even, recur using half that value;
otherwise, recur using half the value rounded up.

The execution here is

i = 12; recur with 12/2, or 6.
i = 6; return -f(6)

If you want to trace the execution, then use a very old, low-tech debugging technique: stick in print statements to trace the execution and data flow. When you enter a routine, print its arguments. Just before you leave, print the value you're about to return. Label each print so you can follow the action.

To help you walk through the process:

To start i = 12 so we enter the third conditional which returns numb(6)

numb(6) returns numb(5) + numb(4)

numb(5) returns numb(4) + numb(3)

numb(4) returns numb(3) + numb(2)

numb(3) returns numb(2) + numb(1)

numb(2) returns numb(1) + numb(0) = numb(1) + (-1)

numb(1) returns numb(0) + numb(-1) = (-1) + (-1) = (-2)

Now we can start walking back up the call stack.

numb(2) returns numb(1) + numb(0) = (-2) + (-1) = (-3)

numb(3) returns numb(2) + numb(1) = (-3) + (-2) = (-5)

...ect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM