下面是五种实现斐波那契数列的方法
循环
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; }();