简体   繁体   English

C中的尾递归

[英]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 )        
       {                       
        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 这是一个定义的链接: 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. 在你发布的代码中,函数做的最后一件事是对它自己进行递归调用,所以通过这个定义,它是尾递归的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM