java - Recursion wrong output -
i given following code
int go(int x){ if (x<1) return 1; else return x + go(x-2) + go(x-3); }
the answer 7
calling go(3)
but everytime (i have hand) 8. logic:
3 + go(1) + go(0)/1 = 3 + go(1) + 1(because 0 less 1)
then,
3 + go(-1) = 3 + 1
therefore,
3 + 4 + 1 = 8.
what doing wrong?
it sounds made mistake go(1) = 3 + go(1-2)
actual formula go(1) = 1 + go(1-2) + go(1-3)
.
go(3) = 3 + go(1) + go(0) = 3 + go(1) + 1 = 3 + (1 + go(-1) + go(-2)) + 1 = 3 + (1 + 1 + 1) + 1 = 7
Comments
Post a Comment