The following is the Javascript basics tutorial column to introduce the three methods of JS to realize the Fibonacci sequence number, I hope it will be helpful to friends in need!
Three methods of implementing Fibonacci columns in JS
How do you realize the Fibonacci series
1,1,2,3,5,8…
f(n)=f(n-1) + f(n-2)
Method 1:
function f(n){ if(n == 1 || n == 0){ return 1; } return f(n-1) + f(n-2); } index.html
Give two more solutions for comparison
Method 2:
function f(n ) { var arr = []; var value = null; function _f(n) { if (n == 1 || n == 0) { return 1; } if (arr[n]) return arr[n]; value = _f(n - 1) + _f(n - 2); arr[n] = value; return value; } return _f(n); } Method 2
Another simpler way is to use array storage
Method 3:
function fn(n) { var dp = new Array(n + 1); dp[0] = dp[1] = 1; for (let i = 2, length = dp.length; i <length; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[n]; }