简体   繁体   English

尾递归,下面的代码片段尾递归吗?

[英]Tail recursion, is the follow snippet tail recursive?

I'm learning about tail recursion, and before I hand in this problem, I'd like a yes / no answer to whether the code snippet is tail recursive or not.我正在学习尾递归,在我提交这个问题之前,我想要一个是/否的答案来判断代码片段是否是尾递归。

int fib_in(int n, int current, int prev) {
    if (n == 1 || n == 2) { // n = 1 or 2 both gives fib number 1
        return current;
    }
    return fib_in(n - 1, current + prev, current); // recursive call, current gets updated and new prev is the current, so were going backwards if that makes sense
}

int fib(int n) {
   return fib_in(n, 1, 1); // 1 and 1 is the 2 first fib numbers so theyll be used as base cases
}

int main(void) {
    int n, f;
    printf("the nth number: ");
    scanf("%d", &n);

    // call fib function
    f = fib(n);
    printf("%d \n", f);
    return 0;
}

I definitely think it is, but I made this function in response to another homework assignment, before we learned about tail recursion, so I would've used a technique I didn't know existed.我绝对认为是这样,但是在我们了解尾递归之前,我制作了这个 function 以响应另一个家庭作业,所以我会使用一种我不知道存在的技术。 Which is why I'm kinda confused.这就是为什么我有点困惑。

This answer does a pretty good job of explaining what tail recursion is.这个答案很好地解释了尾递归是什么。 Particularly note:特别注意:

In tail recursion , you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step.尾递归中,您首先执行计算,然后执行递归调用,将当前步骤的结果传递给下一个递归步骤。 This results in the last statement being in the form of (return (recursive-function params)) .这导致最后一条语句采用(return (recursive-function params))的形式。 Basically, the return value of any given recursive step is the same as the return value of the next recursive call .基本上,任何给定递归步骤的返回值与下一个递归调用的返回值相同

Look at your code again.再看看你的代码。 Does your code fit this description?你的代码符合这个描述吗?

Yes, it is tail recursive.是的,它是尾递归的。 fib_in() calls itself and doesn't perform any additional computations before returning. fib_in()调用自身并且在返回之前不执行任何额外的计算。

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

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