# Ultra fast fibonacci function in C++! :)

This topic is 2778 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.

##### Share on other sites
Prefect's solution and the OP's solution are the same in some sense. If you write the recurrence in matrix form, and you diagonalize the matrix to speed up exponentiation, you'll get the OP's formula.

A = P*D*P^-1
A^n = P*D*P^-1*P*D*P^-1*...*P*D*P^-1 = P*D^n*P-1

1. 1
2. 2
3. 3
4. 4
Rutin
15
5. 5

• 13
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633724
• Total Posts
3013556
×