开发者

Tail recursion in C

I was trying to write recursion function,to find factorial of a number.

    int factorial(int input,int *answer)
    {
       if ( input ==0 )        
      开发者_StackOverflow中文版 {                       
        return 0;
       }

       *answer  = *answer * input;
       factorial(input -1, answer);
    }

What will you say about this function? Is it tail recursive?


When doing tail recursive functions (especially tail recursive functions) it is often helpful to have a helper function in addition to another function which has a more friendly interface. The friendly interface function really just sets up the less friendly function's arguments.

static unsigned factorial_helper(unsigned input, unsigned acc) {
       if (intput == 0) {
           return acc;
       }
       return factorial_helper(input-1, acc * input);
}

unsigned factorial(int input) {
    if (input < 0) {
        do_something_bad();
    }
    return factorial_helper(input, 1);
}

By passing an accumulator value you avoid having to use pointers or do any computations upon returning from called functions, which makes the functions truely tail recursive.


Here's a link with a definition: http://phoenix.goucher.edu/~kelliher/cs23/feb21.html

"A function is tail recursive if the very last thing it does is make its recursive call."

In the code you posted, the last thing the function does is make a recursive call to itself, so by this definition, it is tail-recursive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜