This is the best way to compute the nth Fibonacci number, it uses the matrix form of Fibonacci and then use exponentiation by squaring, the total running time is O(logn):
It doesn't uses double as the famous formula floor(phi^n/sqrt(5)+0.5) which is also O(logn)
#include <iostream>
#include <vector>
using namespace std;
/*
2 by 2 matrix multiplication function modulo M:
*/
vector<long long> mul(vector<long long> A, vector<long long>B, long long Modulo)
{
vector<long long> R(4,0);
R[0]=(A[0]*B[0]+A[1]*B[2]) % Modulo;
R[1]=(A[0]*B[1]+A[1]*B[3]) % Modulo;
R[2]=(A[2]*B[0]+A[3]*B[2]) % Modulo;
R[3]=(A[2]*B[1]+A[3]*B[3]) % Modulo;
return R;
}
/*
Matrix exponentiation by sqaring modulo M:
*/
vector<long long> poww(vector<long long> A, long long m, long long Modulo)
{
if(m==1)
return A;
vector<long long> Z = poww(A,m/2,Modulo);
if(m%2==0)
{
return mul(Z,Z,Modulo);
}
else
{
return mul(mul(Z,Z,Modulo),A,Modulo);
}
}
/*
function to set a 2*2 matrix in a vector<int> of size 4
*/
vector<long long> setM(long long a, long long b, long long c, long long d)
{
vector<long long> R(4,0);
R[0]=a;
R[1]=b;
R[2]=c;
R[3]=d;
return R;
}
/*
compute the nth Fibonacci number modulo M
*/
long long F(long long n, long long Modulo)
{
if(n<=1)return n;
n=n-1;
vector<long long> A=setM(1,1,1,0);
vector<long long> B=setM(1,0,0,0);
vector<long long> C=mul(poww(A,n,Modulo),B,Modulo);
return C[0];
}
int main()
{
cout << F(100000,100000)<< endl;
}