Using recursion to sum numbers

后端 未结 16 2373
轮回少年
轮回少年 2021-02-05 15:45

I have just been studying the concept of recursion and I thought that I would try a simple example. In the following code, I am attempting to take the numbers: 1, 2, 3, 4, 5, an

16条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 16:15

    Others already noted the error, and I will elaborate on recursion.

    Although C# does not currently perform tail call optimization (although IL has special tail instruction), it's worth mentioning that tail recursion is generally a good thing.

    Tail recursion is a special case of recursion in which the last operation of the function, the tail call, is a recursive call. Since the last call is the recursive call there is no need to preserve stack frame of the calling function and the compiler can easily use this information to generate machine instruction such that the stack doesn't grow at all. So it can basically turn recursive function into an iterative one.

    Rewriting your code to support tail recursion can be done as follws:

    static int Sum(int result, int value)
    {
        if(value == 0)
            return result;
    
        return Sum(result + 1, value - 1);
    }
    

提交回复
热议问题