Sword refers to the Fibonacci series of Offer

Source: Internet
Author: User

Sword refers to the Fibonacci series of Offer

All textbooks of the Fibonacci series are available, and will basically appear in the section of recursion. But it doesn't mean that recursion is the best solution of Fibonacci, but because it can better interpret what recursion is. However, this method is not used in real software development. The biggest benefit of recursion is conciseness, which converts large problems into small ones. It is well understood at a macro level. However, the efficiency of recursion is also worth exploring. Recursion requires the system to keep pushing the stack itself, saving the intermediate amount and status, and calling the function also requires time and space. Therefore, there is a problem with efficiency. In addition, the stack capacity opened by each process is limited. If the stack is too large, overflow may occur. For example, if n = 5000, the loop algorithm can find the correct value, but recursion will lead to stack explosion. Another point is repetitive computing. The principle of recursion is to convert a big problem into a small problem, but overlap may occur when it is converted into a small problem, which leads to a straight decline in efficiency.

We can define an array a [3] = {0, 1}; a [0] = 0; a [1] = 1; when n> = 2 is a loop: a [2] = a [0] + a [1]; a [2] = a [1]; a [1] = a [0]; pay attention to the order of values. 9-degree OJ 10 MS.

#include 
 
  #include 
  
   using namespace std;long long Feibonacci(int n){    long long a[3]={0,1},i;    if(n<=1)    return a[n];    for(i=2;i<=n;i++)    {        a[2]=a[0]+a[1];        a[0]=a[1];        a[1]=a[2];            }    return a[2];}int main(){   //freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin);    int n;    while(cin>>n)    cout<
   
    


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.