The beauty of Programming

Source: Internet
Author: User

The following recursive formula is given:

The above is the classic Fibonacci series. The recursive solution is given below:

[CPP]
View plaincopyprint?
  1. Int Fibonacci (int n)
  2. {
  3. If (n <= 0)
  4. Return 0;
  5. Else if (n = 1)
  6. Return 1;
  7. Else
  8. Return maid (n-1) + maid (n-2 );
  9. }

We know that the above solution calculates every F (n) twice. We can only calculate once and make a cache. Of course, this is acceptable. As follows:

[CPP]
View plaincopyprint?
  1. Int tmp1 = 1; // temporary variable, save the intermediate result
  2. Int tmp2 = 0;
  3. Int TMP;
  4. Int Fibonacci (int n)
  5. {
  6. Int F;
  7. For (INT I = 2; I <= N; ++ I)
  8. {
  9. TMP = tmp1 + tmp2;
  10. Tmp2 = tmp1;
  11. Tmp1 = TMP;
  12. }
  13. Return TMP;
  14. }

The above uses the cyclic method, which accelerates the time complexity.

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.