Published
Edited
Jul 28, 2020
1 star
Insert cell
md`# 尾递归`
Insert cell
md`## 实现斐波那契数列`
Insert cell
md`1.普通递归实现`
Insert cell
function fib1(n){
if(n <=2){
return 1;
}
return fib1(n-1) + fib1(n-2);
}
Insert cell
result1 = fib1(5);
Insert cell
md`2.循环实现`
Insert cell
function fib2(n){
if(n <=2){
return 1;
}
let a=1,
b=1;
for(let i=3; i<=n; i++){
let tmp = b;
b = a+ b;
a = tmp;
}
return b;
}
Insert cell
result2 = fib2(6);
Insert cell
md`3.尾递归`
Insert cell
function fib3(n){
const fibFunc = (a,b,n) => {
if(n===1){
return a;
}
return fibFunc(b,a+b,n-1);
}
return fibFunc(1,1,n);
}
Insert cell
result3 = fib3(5);
Insert cell
md`## 阶乘实现`
Insert cell
md`1.普通实现`
Insert cell
function factorial1(n){
if(n<=1){
return 1;
}
return n * factorial1(n-1);
}
Insert cell
f1 = factorial1(3);
Insert cell
md`2.尾递归实现`
Insert cell
function facFunc(a,n){
if(n<=1){
return a;
}
return facFunc(a*n,n-1);
}
Insert cell
function factorial2(n){
return facFunc(1,n);
}
Insert cell
f2 = factorial2(3);
Insert cell
md`3.尾递归实现--柯里化`
Insert cell
function currying(fn,n){
return function(m){
return fn.call(this,n,m)
}
}
Insert cell
factorial3 = currying(facFunc,1);
Insert cell
f3 = factorial3(3);
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more