Two common methods of JS realizing Fibonacci-cut sequence

Source: Internet
Author: User

The Fibonacci sequence is: 1 1 2 3 5 8 ..., the following number is the first two digits of the and, and the second number is 1, with JS implementation

Two methods, one through the common recursive call, the second not through recursion, but through a powerful closure implementation.

1. Recursive implementations

// Fab 1 1 2 3 5 8            function Fab (num) {                if(num==1 | | num==2) {                    return 1;                } Else {                    return Fab (num-1) +fab (num-2);                }            }            Alert (Fab (5))

2. Closure implementation. Closures are mainly: 1. Simulating object-oriented encapsulation data 2. Save the data, because if you define i,j outside the function, it will become a global variable, unsafe, because it will be called to modify, and

Closures can be a good package of data, without recursion can achieve the same function, more commonly used.

 //Closures1. Simulating object-oriented encapsulation data 2. Saving Data            varFIB = (function () {                vari = 1; varj = 1; return function(n) {varres =J;  for(varK = 3; K <= N; k++) {res= i +J; I=J; J=Res; }                    returnRes;            }            })(); document.write (FIB (5));

Two common methods of JS realizing Fibonacci-cut sequence

Related Article

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.