1024programmer JavaScript Three ways to implement Fibonacci columns in JS

Three ways to implement Fibonacci columns in JS

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];
 }

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/three-ways-to-implement-fibonacci-columns-in-js/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索