Last active
December 29, 2016 18:57
-
-
Save viebel/cbd1cf8dce1ee99180285011b2a9753b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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