js递归求阶乘、斐波那契数列

1、求一个数的阶乘

阶乘:n! = n * (n - 1)!,0! = 1

function mul(n) {
if(n==1||n==0){
return 1;
}
return n * mul(n-1);
}

mul(5);//120

//mul(5) ==> 5 * mul(4) 
//mul(4) ==> 4 * mul(3)
//mul(3) ==> 3 * mul(2)
//mul(2) ==> 2* mul(1)

//求到1的阶乘在逐层往上返回
//mul(2) ==> 2* 1 ==2
//mul(3) ==> 3 * mul(2) == 6
//mul(4) ==> 4 * mul(3) == 24
//mul(5) ==> 5 * mul(4) == 120

递归:最先求的值最后返回,且递归函数必须有终止的条件

2、斐波那契数列:是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89从第3项开始,每一项都等于前两项之和

fn(n) == fn(n-1) + fn(n-2)

function fn(n){
if(n==1 || n==2) {
return 1;
}
return fn(n-1) + fn(n-2);
}


fn(5);

//fn(5) ==> fn(4) + fn(3)
//fn(4) ==> fn(3) + fn(2)
//fn(3) ==> fn(2) + fn(1) 

//fn(3) ==> 1 + 1 ==>2
//fn(4) ==> fn(3) + 1 ==>3
//fn(5) ==> fn(4) + 2 ==>5

 

你可能感兴趣的:(js)