1250 Fibonacci series, 1250fibonacci Series
Time Limit: 1 s space limit: 128000 KB title level: DiamondQuestionView running resultsDescriptionDescription
Definition: f0 = f1 = 1, fn = fn-1 + fn-2 (n> = 2 ). {Fi} is called the Fibonacci series.
Enter n and find fn mod q. 1 <= q <= 30000.
Input description
Input Description
The first row is a number T (1 <=t <= 10000 ).
The following T rows have two numbers in each row, n, q (n <= 109, 1 <= q <= 30000)
Output description
Output Description
The file contains T rows, and each line corresponds to one answer.
Sample Input
Sample Input
3
6 2
7 3
7 11
Sample output
Sample Output
1
0
10
Data range and prompt
Data Size & Hint
1 <= T <= 10000
N <= 109, 1 <= q <= 30000
CATEGORY tag
Tags click here to expand
The simplest matrix, rapid power-optimized DP,
Exit the Fibonacci matrix and run the matrix's quick power,
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<algorithm> 6 using namespace std; 7 void read(int &n) 8 { 9 char c='+';int x=0;bool flag=0;10 while(c<'0'||c>'9'){c=getchar();if(c=='-')flag=1;}11 while(c>='0'&&c<='9'){x=x*10+(c-48);c=getchar();}12 flag==1?n=-x:n=x;13 }14 void Matrix_mul(int a[2][2],int b[2][2],int mod)15 {16 int c[2][2];17 memset(c,0,sizeof(c));18 for(int i=0;i<2;i++)19 for(int j=0;j<2;j++)20 for(int k=0;k<2;k++)21 c[i][j]=(c[i][j]+(a[i][k]*b[k][j])%mod)%mod;22 for(int i=0;i<2;i++)23 for(int j=0;j<2;j++)24 a[i][j]=c[i][j];25 }26 int Matrix_fastpow(int n,int q)27 {28 int a[2][2]={1,1,1,0};29 int ans[2][2]={1,0,1,0};30 while(n)31 {32 if(n&1)33 Matrix_mul(ans,a,q);34 Matrix_mul(a,a,q);35 n>>=1;36 }37 //cout<<ans[0][1]<<endl;38 return ans[0][1];39 }40 int main()41 {42 int T,n,q;43 read(T);44 while(T--)45 {46 read(n);read(q);47 n++;48 printf("%d\n",Matrix_fastpow(n,q));49 }50 return 0;51 }