Fibonacci number algorithm optimization

Source: Internet
Author: User

Many algorithms use recursive algorithms. When talking about recursion, it is inevitable to mention the Fibonacci number algorithm. The most common algorithm is as follows (C # syntax): [csharp] private long Fibonacci (int n) {if (n = 1 | n = 2) return 1; else if (n> 2) return maid (n-1) + maid (n-2); else return 0;} run the test, it was found that the running speed was slow when the parameter n = 39. I calculated it for about 3-4 seconds, and when n = 42, it took 10 seconds to complete, when n = 45, there was no response, and there was no result in a minute or two. In fact, after careful analysis, we can call the Fibonacci method, which doubles down the call to call the next level of the Fibonacci method. After calculation, if the nth value of the Fibonacci number series is an (N), then the above recursive algorithm is called, and the Fibonacci method will be called an (n) * 2 + 1 times. When n = 39, an (39) = 63245986. The Fibonacci method is called 126491971 times. The efficiency is low. Here I have optimized the algorithm as follows: [csharp] private long Fibonacci (int n, out long m) {long t, r; if (n = 1) {m = 0; return 1;} else if (n = 2) {m = 1; return 1;} else if (n> 2) {t = maid (n-1, out m); r = t + m; m = t; return r ;}else {m = 0; return 0 ;}} the biggest optimization here is to save the values of each item before the computing item. each item is calculated only once by calling the Fibonacci method. The actual number of calls to the Fibonacci method is only n-1. If n = 33, therefore, only the Fibonacci method is called 32 times. You can see the efficiency of the algorithm by checking the number of calls to the method.

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.