Recursion in C, understand recursion example

后端 未结 6 1320
轮回少年
轮回少年 2021-01-27 20:30

i am having trouble understanding this example. I cant figure out what actually happens after a certain point.

Here is the code, the result is supposed to be 4.

6条回答
  •  一生所求
    2021-01-27 21:02

    You can reason about this problem by substituting and simplifying.

    You start off calling recursion(9), lets substitute 9 for i and reduce

    recursion(9)
    ->  9 > 1 ? 9 - recursion(9/2) : 3
    ->  true ? 9 - recursion(4) : 3
    ->  9  - recursion(4)
    

    now you do recursion(4), to simplify this you can repeat the process...

    recursion(4)
    ->  4 > 1 ? 4 - recursion(4/2) : 3
    ->  true  ? 4 - recursion(2) : 3
    -> 4 - recursion(2)
    
    recursion(2)
    -> 2 > 1 ? 2 - recursion(2/2) : 3
    -> true ? 2 - recursion(1) : 3
    -> 2 - recursion(1)
    
    recursion(1)
    -> 1 > 1 ? ... : 3
    -> false ? ... : 3
    -> 3
    

    Here you got a final result, so substitute it back in to recursion(1)

    2 - 3 -> -1
    

    and recursion(2)

    4 - -1 -> 5
    

    and recursion(4)

    9 - 5 -> 4
    

提交回复
热议问题