The Fibonacci sequence is a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34… Mathematically, the Fibonacci sequence is defined recursively as follows: F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2) (n ≥ 2, n∈ N*).

Method 1 (Dynamic programming) :

/** * @function fibArr(prod) {if (prod < 2) { return prod; } const numArr = [0, 1]; for (let i = 2; i <= prod; i++) { numArr.push(numArr[0] + numArr[1]); numArr.splice(0, 1); } return numArr[1]; }Copy the code

Method 2 (recursion) :

/** * @description Fibonacci recursion * @param {number} num a positive integer * @returns Fibonacci number */ function fib(num) {if (num < 2) {return  num; } return fib(num - 1) + fib(num - 2); }Copy the code

Method 3 (general formula) :

/ / function fibo(num) {if (num < 2) {/ / function fibo(num) {if (num < 2) {/ / function fibo(num) { return num; } if (num === 2) { return 1; } return ((1 / Math.sqrt(5)) * (((1 + Math.sqrt(5)) / 2) ** num - ((1 - Math.sqrt(5)) / 2) ** num)).toFixed(); }Copy the code

The original link: www.wansongtao.com/blog/detail…