斐波那契数列, 这个数列从第3项开始,每一项都等于前两项之和。
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
递归 :
function fibonacci(n, first, second) { if(n == 1) { return first || 0; }else if(n == 2){ return second || 1; } else { return fibonacci(n - 1, first, second) + fibonacci(n - 2, first, second); } } var fb_sum = fibonacci(10, 0, 1); console.log(fb_sum); //34
非递归:
function fibonacci_2(n, first, second){ if(n == 1) return first || 0; if(n == 2) return second || 0; var sum = second, temp = 0, lastSum = first; for(var i = 2; i < n; i++){ temp = sum; sum += lastSum; lastSum = temp; } return sum; } var fb_sum = fibonacci_2(10, 0, 1); console.log(fb_sum); // 34