zoukankan      html  css  js  c++  java
  • 453

    w调用函数次数的计算。

    JavaScript: The Good Parts

    <script>
    var w = 0;
    var w0 =0;
    var w10 =0;

    var fibonacci = function (n) {
    w++
    console.log(n)
    if(n==0)w0++
    if(n==10)w10++

    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
    };

    for (var i = 0; i <= 10; i += 1) {
    document.writeln('// ' + i + ': ' + fibonacci(i));
    }

    console.log(w)
    console.log(w0)
    console.log(w10)

    </script>

    0 1
    1 1
    2 1 1 2 1+2=3
    3 2 1 3 1+4=5
    4 3 2 5 1+8=9
    5 5 3 8 1+14=15
    6 8 5 13 1+24=25
    7 13 8 21 1+40=41
    8 21 13 34 1+66=67
    9 34 21 55 1+108=109
    10 55 34 89 1+176=177
            453


    <script type="text/javascript">
    <!--
        var w = function(n){
            return n<2 ? 1 : w(n-1)+w(n-2) 
        }
    //-->
    </script>

    4.15. Memoization

    Functions can use objects to remember the results of previous operations, making it possible to avoid unnecessary work. This optimization is called memoization. JavaScript's objects and arrays are very convenient for this.

    Let's say we want a recursive function to compute Fibonacci numbers. A Fibonacci number is the sum of the two previous Fibonacci numbers. The first two are 0 and 1:

    var fibonacci = function (n) {
        return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
    };
    
    for (var i = 0; i <= 10; i += 1) {
        document.writeln('// ' + i + ': ' + fibonacci(i));
    }
    
    // 0: 0
    // 1: 1
    // 2: 1
    // 3: 2
    // 4: 3
    // 5: 5
    // 6: 8
    // 7: 13
    // 8: 21
    // 9: 34
    // 10: 55

  • 相关阅读:
    TIM时钟频率计算
    时钟节拍tick
    Continue作用
    struct结构体的字节长度,字节对齐
    IAR所包含的头文件位置
    Oracle存储过程给变量赋值的方法
    DataTable如何去除重复的行
    C#遍历窗体所有控件或某类型所有控件
    SqlServer无备份下误删数据恢复
    45.4.7 序列:USER_SEQUENCES(SEQ)
  • 原文地址:https://www.cnblogs.com/rsapaper/p/6395941.html
Copyright © 2011-2022 走看看