Home > Web Front-end > JS Tutorial > Three ways to implement Fibonacci numbers in JS

Three ways to implement Fibonacci numbers in JS

藏色散人
Release: 2020-06-06 14:34:20
forward
2364 people have browsed it

The following is the javascript basic introduction tutorial 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

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
Copy after login

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

方法二
Copy after login

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];
}
Copy after login

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!

Related labels:
js
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template