首页 > 代码库 > 养兔子Fibo函数优化

养兔子Fibo函数优化

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /* var cache = (function createCache() {
     var data = http://www.mamicode.com/[];"_name","zs");*/


    /* function createCache() {
     var arr = [];
     return function cache(key, value) {
     if (arr.length >= 3) {
     var temp = arr.shift();
     delete cache[temp];
     }
     arr.push(key);
     cache[key] = value;
     }
     }
     var cache = createCache();
     cache(‘_name1‘, ‘z‘);
     cache(‘_name2‘, ‘zs‘);
     cache(‘_name3‘, ‘zds‘);
     cache(‘_name4‘, ‘zadf‘);*/
    var month =  prompt("请输入月数:")
    function fibobo(x) {
        var arr = [1, 1];
        // var arr = [];
        (function fib(n) {
            if (n === 0 || n === 1) {
                return 1;
            }
            if (!arr[n]) {
                arr.push(fib(n - 1) + fib(n - 2));
                return arr[n];
            } else {
                return arr[n];
            }
        })(x);

        // console.log(arr)

        return arr[x - 1];
    }
    // var begin1 = +new Date();
    console.time(‘优化后方案‘)
    console.log(month+"个月后有"+fibobo(month)+"只兔子");
    // var end1  = +new Date();
    // console.log (end1-begin1);
    console.timeEnd(‘优化后方案‘)
    function fib(n) {
        if (n<=2){
           return 1 ;
        }
        return fib(n -1 ) + fib(n - 2);
    }
    console.time(‘优化前方案‘)
    console.log(month+"个月后有"+fib(month)+"只兔子");
    console.timeEnd(‘优化前方案‘);
   /* function Fib ( n ) {
        if ( n === 1 || n === 2 ) return 1;
        return Fib ( n - 1 ) + Fib ( n - 2 );
    }
    console.time(‘c‘)
    console.log(month+"个月后有"+Fib(month)+"只兔子");
    console.timeEnd(‘c‘);
    */
    /*
     var o = {
     a: 1,
     b: 2
     }
     var o1 = {};
     for (var key in o) {
     o1[key] = o [key]
     }
     console.log(o1)
     console.log(o.length)*/

</script>
</body>
</html>

 

养兔子Fibo函数优化