js递归案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script>
    //求n个数的累加
    //getSum(1) = 1
    //getSum(2) = 2+1
    //getSum(3) = 3+2+1
    //getSum(3) = 3+getSum(2)
    //getSum(n) = n+getSum(n-1)
    function getSum(n) {
        if (n === 1) {
            return 1;
        }
        var sum = n + getSum(n - 1);
        return sum;
    }
    //console.log(getSum(5));

    //求n的阶乘
    //getJC(1) = 1
    //getJC(2) = 2*1
    //getJC(3) = 3*2*1
    //getJC(3) = 3*getJC(2)
    //getJC(n) = n*getJC(n-1)
    function getJC(n) {
        if (n === 1) {
            return 1;
        }
        var jc = n * getJC(n - 1);
        return jc;
    }
    //console.log(getJC(3));
    //求Fibonacci的第n个数1 1 2 3 5 8 13 21...
    //2 = 1 + 1
    //getFib(3) = getFib(1)+getFib(2)
    //3 = 2 + 1
    //getFib(4) = getFib(2)+getFib(3)
    //getFib(n) = getFib(n-2)+getFib(n-1)
    function getFib(n) {
        if (n === 1 || n === 2) {
            return 1;
        }
        var fib = getFib(n - 2) + getFib(n - 1);
        return fib;
    }
    console.log(getFib(12));//144

</script>
</body>
</html>
上一篇:学妹问,学网站开发还是打 ACM?


下一篇:SpringSecurity学习笔记