[英]tail recursive version for Fibonacci-like function
I am having trouble understanding the concept of tail recursion, I want to make a tail recursive version for Fibonacci-like function, p1= n-3 , p2= n-2, fx( p1 ) + fx( p2 ) and so far this is what I came up with but I don't know if it's a correct approach, can someone help me out, any help would be appreciated p1= n-3 , p2= n-2 Long doCalc( long n ) { return n == 0 ?我无法理解尾递归的概念,我想为类斐波那契函数 p1= n-3 , p2= n-2 , fx( p1 ) + fx( p2 ) 制作一个尾递归版本,到目前为止是我想出的,但我不知道这是否是正确的方法,有人可以帮助我吗,任何帮助将不胜感激 p1= n-3 , p2= n-2 Long doCalc( long n ) { return n = = 0 ? 0 : ( n == 1 ? 1 : ( n == 2 ? 1 : (make( p1 ) + make( p2 )) ) );
0 : ( n == 1 ? 1 : ( n == 2 ? 1 : (make( p1 ) + make( p2 )) ) ); }
}
the code outputs the correct result代码输出正确的结果
but when i implement the tail recursive , my approach was split and conquer, but it's not working and the output are wrong但是当我实现尾递归时,我的方法是分而治之,但它不起作用并且输出错误
Long factor3(Long n, Long a)
{
if( n == 0){
return 0l;
} else if( n == 1 || n == 2) {
return a;
}
return factor3(p1, n + a);
}
Long factor2(Long n, Long a)
{
if( n == 0){
return 0l;
} else if( n == 1 || n == 2) {
return a;
}
return factor2(p2, n + a);
}
Sadly, I do not have enough reputation to comment, but to answer your question:可悲的是,我没有足够的声誉来发表评论,但要回答您的问题:
First of all, this link really helps to understand how to achieve the solution.首先,这个链接确实有助于理解如何实现解决方案。
It's pretty much: Since you start with (a,b,c) = (0,1,1) and you want to derive the next number by adding the second and third last, your next number (hypothetically d) would be a+b差不多:由于您从 (a,b,c) = (0,1,1) 开始,并且您想通过添加倒数第二个和第三个来得出下一个数字,因此您的下一个数字(假设为 d)将是 a+ b
so (a,b,c,d) = (a,b,c,a+b)所以 (a,b,c,d) = (a,b,c,a+b)
Which means when you look at the next iteration, you "shift" everything left and your next call will be (b,c,a+b) as stated by Andrey这意味着当您查看下一次迭代时,您将“移动”所有内容,并且您的下一次调用将是 (b,c,a+b),如 Andrey 所述
I believe the reasoning is following:我相信推理如下:
public static Long doCalcRecursive(long n) {
return n == 0 ? 0 : (n == 1 ? 1 : (n == 2 ? 1 : (doCalcRecursive(n - 3) + doCalcRecursive(n - 2))));
}
public static Long doCalcIterative(long n) {
long a = 0, b = 1, c = 1, d;
if (n == 0) {
return a;
}
for (int i = 2; i <= n; i++) {
d = a + b;
a = b;
b = c;
c = d;
}
return b;
}
so, (a,b,c)
turns into (b,c,a+b)
and tail recursion is:所以,
(a,b,c)
变成(b,c,a+b)
并且尾递归是:
public static long doCalcTail(long n, long a, long b, long c) {
return n == 0 ? a : n == 1 ? b : n == 2 ? c : doCalcTail(n - 1, b, c, a + b);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.