斐波拉契数列
斐波拉契数列
- a1 = 1
- a2 = 1
- an = an-1 + an-2 (n > 2时)
第 n 项
// 递归写法 (性能极差, 会有很多重复计算) 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; }