# 尾递归是个什么鬼

function foo(data) {
a(data);
return b(data);
}


function foo1(data) {
return a(data) + 1;
}
function foo2(data) {
var ret = a(data);
return ret;
}
function foo3(data) {
var ret = a(data);
return (ret === 0) ? 1 : ret;
}


常规的斐波那契数列算法可能是这样的：

int fib(int n) {

if (n <= 2) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}


/**
计算第n位斐波那契数列的值

@param n 第n个数
@param acc1 第n个数
@param acc2 第n与第n+1个数的和
@return 返回斐波那契数列值
*/
int tailfib(int n,int acc1,int acc2) {
if (n < 2) {
return acc1;
}

return tailfib(n-1,acc2,acc1 + acc2);
}


int main(int argc, const char * argv[]) {
clock_t start,finish;

start = clock();
printf("计算结果：%d\n", fib(45));
finish = clock();
printf("花费时间--------%lu\n",finish - start);

start = clock();
printf("计算结果：%d\n", tailfib(45,1,1));
finish = clock();

printf("花费时间--------%lu\n",finish - start);
return 0;

}


计算结果：1134903170

Program ended with exit code: 0


int fac(int n) {
if (n == 1) {
return 1;
}
return fac(n-1) * n;
}


int tailfac(int n,int sum) {
if (n == 1) {
return sum;
}
return fac(n-1, n * sum);
}

复杂度为O(1)

int main(int argc, const char * argv[]) {
clock_t start,finish;

start = clock();
printf("计算结果：%d\n", fac(16));
finish = clock();
printf("花费时间--------%lu\n",finish - start);

start = clock();
printf("计算结果：%d\n", tailfac(16,1));
finish = clock();

printf("花费时间--------%lu\n",finish - start);
return 0;

}


计算结果：2004189184



posted @ 2017-10-24 13:56  zhanggui  阅读(8936)  评论(13编辑  收藏  举报