The usage analysis of Fibonacci sequence of recursive form and non-recursive form _c language

Source: Internet
Author: User
Copy Code code as follows:

<span style= "font-size:32px" > Implementation of Fibonacci Sequence by recursive form and non-recursive form </SPAN>

Copy Code code as follows:

#include "stdafx.h"
#include <iostream>
using namespace Std;
Fibonacci sequence in recursive form
int fibonaccirecursion (int n)
{
if (n = = 1 | | n ==2)
{
return 1;
}
if (n > 2)
{
Return Fibonaccirecursion (n-1) + fibonaccirecursion (n-2);
}
}
Fibonacci sequence of non-recursive forms
Use an array as an auxiliary space
High efficiency
int Fibonacci (int n)
{
int temp[2];
Temp[0] = 1;
TEMP[1] = 1;
if (n = = 1 | | n = = 2)
{
return 1;
}
Else
{
for (int i = 2; i < n; i + +)
{
int TP = Temp[0] + temp[1];
TEMP[1] = temp[0];
TEMP[0] = TP;
}
return temp[0];
}
}

Test code:
Copy Code code as follows:

int _tmain (int argc, _tchar* argv[])
{
cout << Fibonacci (1) << "<< Fibonacci (2) <<" "<< Fibonacci (3) <<" "<< fib Onacci (4) << ""
<< Fibonacci (5) << "" << Fibonacci (6) << "" << Fibonacci (7) << "" << Fibonacci ( 8) << ""
<< Fibonacci (9) << "" << Fibonacci (+) << Endl;
cout << fibonaccirecursion (1) << "<< fibonaccirecursion (2) <<" "<< fibonaccirecursion (3 ) << "" <<
Fibonaccirecursion (4) << "" << fibonaccirecursion (5) << "" << fibonaccirecursion (6) << "" & lt;< Fibonaccirecursion (7)
<< "" << fibonaccirecursion (8) << "<< fibonaccirecursion (9) <<" "<< fibonaccirecur Sion (a) << Endl;
return 0;
}

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.