Home>Article>Web Front-end> Three ways to implement Fibonacci numbers in JS
The following is thejavascript basic introductiontutorial column to introduce to you three methods of realizing Fibonacci series in JS. I hope it will be helpful to friends in need!
Three ways to implement Fibonacci numbers in JS
How do you implement Fibonacci numbers?
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
Here are 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); } 方法二
There is also a simpler solution Array storage is used
Method three:
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]; }
Related recommendations: "javascript Advanced Tutorial"
The above is the detailed content of Three ways to implement Fibonacci numbers in JS. For more information, please follow other related articles on the PHP Chinese website!