Home >Web Front-end >JS Tutorial >Implement Fibonacci sequence using javascript

Implement Fibonacci sequence using javascript

藏色散人
藏色散人Original
2021-04-08 15:03:488810browse

Javascript method to implement Fibonacci sequence: 1. Use recursive method to implement, code such as "function fib(n){...}"; 2. Use for loop to implement, code such as "for( var i=2;i

Implement Fibonacci sequence using javascript

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript implements the Fibonacci sequence

The Fibonacci sequence, also known as the golden section sequence, refers to such a sequence: 1, 1, 2, 3, 5, 8, 13, 21... Starting from the 3rd number, each number is equal to the sum of the two numbers before it

Method 1: Recursion

function fib(n){
    if(n==1 || n==2){
        return 1;
    }
    return fib(n-1) + fib(n-2);
}

Method 2: for Loop implementation

function fb(n){
    var res = [1,1];
    if(n == 1 || n == 2){
        return 1;
    }      
    for(var i=2;i<n;i++){
        res[i] = res[i-1] + res[i-2];
    }
    return res[n-1];
}

or

function fb(n){
    var a,b,res;
    a = b = 1;
    for(var i=3;i<=n;i++){
        res = a + b;
        a = b;
        b = res;
    }
    return res;
}

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of Implement Fibonacci sequence using javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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