js computing Fibonacci number

 
/**
 * Requirements: js calculated using the Fibonacci number, time complexity as low as possible. Input digital values ​​of n, the n-bit output of the series
 * 
 * Fibonacci number as follows:
 * 1、2、3、5、8、13、21、34、
 * 
 * Results show:
 8 * input, 34 output
 * 10 input, 89 output
 * Input 20, output 10 946
 */

// no cached version
var calFibonacci = function(n) {
  // number of iterations statistics
  were count = 0;
  function _calFibonacci(n) {
    // number of iterations statistics
    count++;
    if (n === 1) return 1;
    if (n === 2) return 2;

    return _calFibonacci(n-1) + _calFibonacci(n-2);
  }
  var result =  _calFibonacci(n);
  // output iterations statistics
  console.log(count);
  return result;
};

/**
 * Discussion:
 * Recursive What are the advantages and disadvantages?
 */


// cached version
var calFibonacci = function(n) {
  var cache = {};
  // number of iterations statistics
  // var count = 0;
  function _calFibonacci(n) {
    // number of iterations statistics
    // count++;
    if (n === 1) return 1;
    if (n === 2) return 2;

    var first;
    if (cache[n-1]) {
      first = cache[n-1];
    } else {
      first = _calFibonacci(n-1);
      cache[n-1] = first;
    }
    
    var second;
    if (cache[n-2]) {
      second = cache[n-2];
    } else {
      second = _calFibonacci(n-2);
      cache[n-2] = second;
    }

    return first + second;
  }
  var result =  _calFibonacci(n);
  // output iterations statistics
  // console.log(count);
  return result;
};

console.log(calFibonacci(20));

Guess you like

Origin www.cnblogs.com/chuanzi/p/12005918.html