Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
// Calculates the Fibonnacci sequence by fast exponentiation:
// http://rosettacode.org/wiki/Fibonacci_sequence#C.2B.2B
#include <iostream>
inline void fibmul(int* f, int* g)
{
int tmp = f[0]*g[0] + f[1]*g[1];
f[1] = f[0]*g[1] + f[1]*(g[0] + g[1]);
f[0] = tmp;
}
int fibonacci(int n)
{
int f[] = { 1, 0 };
int g[] = { 0, 1 };
while (n > 0)
{
if (n & 1) // n odd
{
fibmul(f, g);
--n;
}
else
{
fibmul(g, g);
n >>= 1;
}
}
return f[1];
}
int main()
{
for (int i = 0; i < 9; ++i)
cout << "fib(" << i << "): " << fibonacci(i) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment