关于著名的Fibonacci函数的两种解法
1.递归(cache优化过后)
function fibonacciByRecursive(n) {
var cache= [0,1];
return (function _fibonacci(n) {
return typeof cache[n] ==='number'?cache[n] :cache[n] =_fibonacci(n -1) +_fibonacci(n -2);
})(n)
}
2.for循环方式,简单高效
function fibonacciByForeach(n) {
var sum = 0, b = 1;
for (var i = 0; i < n; i++) {
sum = sum + b;
b = sum - b;
}
return sum;
}