diff --git a/FIBONACCI.cpp b/FIBONACCI.cpp new file mode 100644 index 0000000..e32a4a0 --- /dev/null +++ b/FIBONACCI.cpp @@ -0,0 +1,26 @@ +// this implementation can find the Nth fibonacci number in O(log N) time! +// Basic use of Matrix Exponentiation +#include +#include +using namespace std; + +#define long long long +const long M = 1000000007; // modulo +map F; + +long f(long n) { + if (F.count(n)) return F[n]; + long k=n/2; + if (n%2==0) { // n=2*k + return F[n] = (f(k)*f(k) + f(k-1)*f(k-1)) % M; + } else { // n=2*k+1 + return F[n] = (f(k)*f(k+1) + f(k-1)*f(k)) % M; + } +} + +main(){ + long n; + F[0]=F[1]=1; + while (cin >> n) + cout << (n==0 ? 0 : f(n-1)) << endl; +}