斐波拉契数列
(n > 2时)
第 n 项
// 递归写法 (性能极差, 首先这个不是纯尾递归,其次Chrome也没有做尾递归优化)
function Fibonacci(n) {
if (n<3) return 1;
return Fibonacci(n-1) + Fibonacci(n-2);
}
// 循环写法
function Fibonacci2(n) {
if (n<3) return 1;
let first, second=1,third=1;
for (let i = 3; i <= n; i ++) {
first = second;
second = third;
third = first + second;
}
return third;
}