Recursive function --- Case: seeking the first 100 Fibonacci numbers

// the Fibonacci column 11235813213455 ... 
    @ Law: Starting from the third number, a number equal to the number of the first two and 
    //       getFib (n-) = getFib ( . 1-n-) getFib + (2-n-) 
    
    @ demand: seeking the first 100 Fibonacei 

    // a method 
    var ARR = []
     function getFib (n-) {
       IF (= n-n-===. 1 || 2 == ) {
         return . 1 
      } 
      IF (ARR [n-]) {
         return ARR [n-] 
      } the else { 
        ARR [n-] = getFib (n--. 1) getFib + (n-- 2 );
         return ARR [n-] 
      }  
    }
    Console .log (getFib ( 100));


    // 方法二:利用递归
    function outer(){
      var arr = []
      function getFib(n) {
        if (n === 1 || n === 2) {
          return 1
        }
        if (arr[n]) {
          return arr[n]
        } else {
          arr[n] = getFib(n - 1) + getFib(n - 2);
          return arr[n]
        }
      }
      return getFib;
    }
    var result = outer();
    the console.log (Result ( 100 )); 


    // getFib;Method three: from anonymous function call using optimized to reduce the use of global variables === binding optimize closure performance (protected variable) 
    var Result = ( function () {
       var ARR = []
       function getFib (n-) {
         IF (= n- || 2. 1 n-=== == ) {
           return . 1 
        } 
        IF (ARR [n-]) {
           return ARR [n-] 
        } the else { 
          ARR [n-] = getFib (n--. 1) getFib + (n-- 2 );
           return ARR [n-] 
        } 
      } 
      return 
    }) (); 
    the console.log (Result ( 100));

 

Guess you like

Origin www.cnblogs.com/lixiaoxue/p/11228587.html