Skip to content

Instantly share code, notes, and snippets.

@viebel
Last active December 29, 2016 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viebel/cbd1cf8dce1ee99180285011b2a9753b to your computer and use it in GitHub Desktop.
Save viebel/cbd1cf8dce1ee99180285011b2a9753b to your computer and use it in GitHub Desktop.
// 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