Use JavaScript to print out the number of Fibonacci (without using global variables)

Source: Internet
Author: User

6 basic topics from Uncle Tom's blog: This is the 4th question- print the Fibonacci number using JavaScript (without global variables)

Key to solving problems:

1, the Law of Fibonacci series

2. Recursion

The law of solving the 1:fibonacci sequence of points
1,1,2,3,5,6,13,19,32.  // starting with item 3rd, each item is the sum of the first two

Solution Point 2: Recursion

Recursion is a complex concept, the problem can not be solved recursively, but the topic requires not to use global variables, so I can only think of recursive method. Simply put, recursion is the function call function itself, but recursive must have an exit, otherwise infinite call down ... Here is a list of Fibonacci series and find the law:

1th Item, 1++= Fibonacci (n-1) + Fibonacci (n-2)

Then its exit is at 1 here, that is, the number of items is less than 2 o'clock, return 1 directly, and no longer call yourself (once you do not call yourself, it means recursion ends)

The following is the implementation code for the problem:

function // show Top N    of Fibonacci function // to find the Fibonacci of the article I        return // The rules for recursion are defined here     }    for (var i=1; i<=n;i++) {        Console.log (Fibo (i));}    } Fibonacci (5);  // 1,1,2,3,5

The answer is complete!

Use JavaScript to print out the number of Fibonacci (without using global variables)

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.