• 13
• 18
• 19
• 27
• 10

Ultra fast fibonacci function in C++! :)

This topic is 2508 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi, I have created a fibonacci generation function, which is not recursive!!

Here it is:

 double fibonacci(unsigned n) { return 0.447213595 * pow(1.61803399, (double)n) - 0.447213595 * pow(-0.618033989, (double)n); } 

Share on other sites
Hi, you may want to double the significant digits in your constants in order to fully utilise double precision! As it is, it will probably break when your result is somewhere in the tens of millions range (at best).

Share on other sites

Hi, I have created a fibonacci generation function, which is not recursive!!

You mean, you've implemented a fairly well-known mathematical formula. As noted, you are going to have problems with precision errors at some point. Also, recursion is not needed for the Fibonacci numbers, anyway: you just generate them sequentially from the beginning. This is perhaps one of the classic examples of how "dynamic programming" techniques can improve the runtime complexity of algorithms.

Share on other sites
For generating really large Fibonacci numbers, you can even go one step further. Write the linear recurrence in matrix form (this is the same matrix you would use to derive the formula that the OP used), and then use repeated squaring to get the desired power of the matrix. Then you just read the result out of the matrix. Asymptotically, this is only really faster if you use one of the fast integer multiplication algorithms, e.g. via gmplib.