什么是斐波那契
斐波那契数列指的是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368........
这个数列从第3项开始,每一项都等于前两项之和
代码实现
function fibonacci() {
var list = [];
return function () {
var i;
if (list.length < 2) {
i = 1;
} else {
i = list[list.length - 1] + list[list.length - 2]
}
list.push(i);
return i;
};
}
var f = fibonacci();
for (var i = 0; i < 10; i++) {
console.log(f());
}
Output:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55