Skip to content

Instantly share code, notes, and snippets.

@nitish1402
Last active August 29, 2015 14:06
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 nitish1402/da6dcaaef666de0b2aad to your computer and use it in GitHub Desktop.
Save nitish1402/da6dcaaef666de0b2aad to your computer and use it in GitHub Desktop.
Fibonacci via matrix exponenetiation
#include<stdio.h>
#define ll long long
void matpower(long long M[2][2],int n){
long long w,x,y,z,a,b,c,d;
long long j=1000000007;
if(n>1){
matpower(M,n/2);
w=((M[0][0]*M[0][0])%j+(M[0][1]*M[1][0])%j)%j;
x=((M[0][0]*M[0][1])%j+(M[0][1]*M[1][1])%j)%j;
y=((M[1][0]*M[0][0])%j+(M[1][1]*M[1][0])%j)%j;
z=((M[1][0]*M[0][1])%j+(M[1][1]*M[1][1])%j)%j;
M[0][0]=w;
M[0][1]=x;
M[1][0]=y;
M[1][1]=z;
if(n%2!=0){
a=((M[0][0]*1)%j+(M[0][1]*1)%j)%j;
b=((M[0][0]*1)%j+(M[0][1]*0)%j)%j;
c=((M[1][0]*1)%j+(M[1][1]*1)%j)%j;
d=((M[1][0]*1)%j+(M[1][1]*0)%j)%j;
M[0][0]=a;
M[0][1]=b;
M[1][0]=c;
M[1][1]=d;
}
}
}
long long fib(long long M[2][2],int n){//function for computation
if(n==1) return 1;
else if(n==2) return 2;
else {matpower(M,n-2);
long long j=1000000007;
return (((M[0][0]*2)%j+(M[0][1]*1)%j)%(j));}
}
int main()
{
int t;
ll m,n;
scanf("%d",&t);
while(t--){
long long M[2][2]={{1,1},{1,0}};
scanf("%lld",&n);
m=fib(M,n);
printf("%lld\n",m);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment