javascript 递归求阶乘

var n = parseInt(window.prompt('input'));
function mul(n) {
if (n === 1 || n === 0) {
return 1
}
return n * mul(n - 1)
}
console.log(mul(n));
n的阶乘 计算公式: n* n-1的阶乘;
输入5
mul(5) => 5* mul(4) => 5 * 24 = 120
mul(4) => 4* mul(3) => 4 * 6 = 24
mul(3) => 3* mul(2) => 3 * 2 = 6
mul(2) => 2* mul(1) => 2 * 1 = 2
已知1的阶乘是1 将这个条件作为出口
版权声明:
作者:东明兄
链接:https://blog.crazyming.com/note/1463/
来源:CrazyMing
文章版权归作者所有,未经允许请勿转载。


共有 0 条评论