Recursion wrong output

醉酒当歌 提交于 2019-12-12 05:20:35

问题


I am given the following code

int go(int x){
   if (x<1)
      return 1;
   else
      return x + go(x-2) + go(x-3);
}

The answer is 7 by calling go(3)but everytime I do it (I have to do it by hand) I get 8. This is my logic:

3 + go(1) + go(0)/1 = 3 + go(1) + 1(because 0 is less than 1)

Then,

3 + go(-1) = 3 + 1

Therefore,

3 + 4 + 1 = 8.

What am I doing wrong?


回答1:


It sounds like you made mistake as go(1) = 3 + go(1-2) where the actual formula is 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



回答2:


go(3)

3 + go(3-2) + go(3-3)

3 + go(1) + go(0)

3 + 1 + go(1-2) + go(1-3) + 1

5 + go(-1) + go(-2)

5 + 1 + 1

7



回答3:


answer is 7 which is correct. 

3 + go(3-2) + go(3-3) 
 = 3 + go(1) + go(0)

 go(0) = 1 

 go(1) = 1 + go(1-2) + go ( 1-3)
       = 1 + go(-1) + go(-2)
       = 1 + 1 + 1 
       = 3 


 = putting all values go(3) = 7 



回答4:


in this recursive method, your base case is x<1, so whenever that is the case 1 will be returned.

The following is how it will be played out.

go(3)== 3 + 3 + 1 == 7
 3 + go(3-2)=>go(1) + go(3-3)=>go(0)
  go(1)==1+1+1==3
    1 + go(1-2)=>go(-1) + go(1-3)=>go(-2)
      go(-1)==1
        1
      go(-2)==1
        1
  go(0)==1
    1

Hope the structure shows how it will be played out. If anything, always try doing out the branches a recursive method creates



来源:https://stackoverflow.com/questions/35835640/recursion-wrong-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!