I have removed the modulus there since any nonegative n
less than 4 will just become n
so I ended up with:
public static int recur (int y)
{
return y <= 3 ?
y :
recur(y-2) + recur(y-1) + 1;
}
I like to start off by testing the base case so what happens for y
when they are 0,1,2,3? well the argument so 0,1,2,3 of course.
What about 4
? Well then it's not less or equal to 3
and you get to replace it with recur(4-2) + recur(4-1) + 1
which is recur(2) + recur(3) + 1
. Now you can solve each of the recur
ones since we earlier established became its argument so you end up with 2 + 3 + 1
.
Now doing this for 12
or 25
is exactly the same just with more steps. Here is 5 which has just one more step:
recur(5); //=>
recur(3) + recur(4) + 1; //==>
recur(3) + ( recur(2) + recur(3) + 1 ) + 1; //==>
3 + 2 + 3 + 1 + 1; // ==>
10
So in reality the recursion halts the process in the current iteration until you have an answer that the current iteration adds together so I could have done this in the opposite way, but then I would have paused every time I now have used a previous calculated value.
You should have enough info to do any y
.