JS Fibonacci sequence

Source: Internet
Author: User

The Fibonacci sequence refers to a sequence of 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ...

This sequence starts with the 3rd item and each item is equal to the sum of the first two items.

1. Recursive algorithm:

    function fib (n) {        if2) {            return  n;        } Else {            return fib (n-1) + fib (n-2);}    }

2. Dynamic Programming Algorithms

function fib (n) {varval = [];  for(vari =0; I <= N; ++i) {Val[i]=0; }        if(n = =1|| n = =2) {            return 1; }Else{val[1] =1; val[2] =2;  for(vari =3; I <= N; ++i) {Val[i]= val[i-1] + val[i-2]; }        returnval[n-1]; }    }

The reason why a dynamic plan needs to use an array is because the dynamic programming algorithm usually needs to save the intermediate results. Dynamically planned solutions are more efficient than recursive solutions when calculating fib (20) and larger numbers.

3. Iterative method

    function fib (n) {        var1;         var 1 ;         var 1 ;          for (var2; i < n; + +i)            {= last + nextlast            ; = Last ;             = result;        }         return result;    }

JS Fibonacci sequence

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.