下面是五种实现斐波那契数列的方法

循环

function fibonacci(n){
 var res1 = 1;
 var res2 = 1;
 var sum = res2;
 for(var i = 1;i < n;i ++){
   sum = res1 + res2;
   res1 = res2;
   res2 = sum;
 }
 return sum;
}

普通递归

function fibonacci (n) {
 if ( n <= 1 ) {return 1};
 return fibonacci(n - 1) + fibonacci(n - 2);
}

尾递归

function fibonacci(n, ac1=1,ac2=1){
  if(n<=1){return ac2}
 return fibonacci(n-1, ac2, ac1 + ac2)
}
Generator 函数和for...of循环
// Generator 函数和for...of循环
function* fibonacci() {
 let [prev, curr] = [0, 1];
  // foo(;;)相当于死循环 等于while(1)
 for (;;) {
  yield curr;
  [prev, curr] = [curr, prev + curr];
 }
}
for (let n of fibonacci()) {
 if (n > 1000) break;
 console.log(n);
}

闭包实现

const fibonacci = function(){
  var mem = [0,1];
  var f = function(n){
    var res = mem[n];
    if(typeof res !== 'number'){
      mem[n] = f(n-1) + f(n-2);
      res = mem[n];
    }
    return res;
  }
  return f;
}();

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!