1250 Fibonacci Series
Time limit: 1 s
space limit: 128000 KB
title level: Diamonds Diamond
Title Description Description
Definition: F0=f1=1, fn=fn-1+fn-2 (n>=2). {fi} is called the Fibonacci sequence.
Enter N and ask FN mod Q. Which 1<=q<=30000.
Enter a description input Description
The first line is a number T (1<=t<=10000). The
following T-lines, two digits per line, n,q (n<=10^9, 1<=q<=30000)
outputs description output Description
The file contains a T line, and each line corresponds to an answer.
sample input to sample
3
6 2
7 3
7 11
sample output Sample outputs
1
0
10
Data Size & Hint
1<=t<=10000
n<=10^9, 1<=q<=30000
The following:
Because N is a 10^9, so it cannot be solved with a simple O (n), we need an algorithm with a greater degree of complexity--matrix multiplication to help.
Let's introduce it briefly:
The matrix multiplication is the complexity of O (Logn), and the object is an N-row m-column and a matrix of M-row P-columns. The matrix multiplication is a matrix of n-rows P-columns, and the first row of the matrix is a sums of the product of each number of rows I of a matrix and the corresponding number of the column J of another matrix. In general, we can use a fast power to speed things up.
Simple matrix multiplication:
for (int i=1, i<=n; i++) for
(int j=1; j<=p; j + +) for
(int k=1; k<=m; k++)
c[i][j]+=a[i][k]*b[k][j];
Regression problem, we need to ask for the Fibonacci sequence of the nth item, you can create two matrices:
Then let's multiply them two, and we can get a matrix like this:
So we can see that, for F[n], it can actually be transferred from such two matrices, and for the B-Matrix, it is transferred from the previous layer, so for f[n] it can be:
Therefore, it can be solved by using the matrix multiplication under the fast power acceleration. (All kinds of strange problems when you pass the argument I hope you will be careful ...) )
Code:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath
> #include <algorithm> using namespace std;
int t,n,q,ans,a[2][2],b[2][2];
int in () {int x=0; char Ch=getchar ();
while (ch< ' 0 ' | | ch> ' 9 ') Ch=getchar ();
while (ch>= ' 0 ' && ch<= ' 9 ') x=x*10+ch-' 0 ', Ch=getchar ();
return x;
} void Init () {a[0][0]=a[0][1]=a[1][0]=1; a[1][1]=0; B[0][0]=b[0][1]=b[1][0]=1;
b[1][1]=0;
} void Matrix (int x[2][2],int y[2][2]) {int c[2][2]={0}; for (int i=0, i<=1; i++) for (int j=0; j<=1; j + +) for (int k=0; k<=1; k++) c[
I][j]= (C[i][j]+x[i][k]*y[k][j])%q;
for (int i=0, i<=1; i++) for (int j=0; j<=1; j + +) Y[i][j]=c[i][j];
} int main () {t=in ();
while (t--) {n=in (), Q=in ();
Init ();
if (n<=1) {printf ("1\n");
Continue
} int y=n-2;
while (y) { if (y&1) matrix (A, b); y>>=1;
Matrix (a,a);
} ans= (b[0][0]+b[0][1])%q;
printf ("%d\n", ans);
} return 0; }