Fibonacci Series
Title 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
The first line is a number T (1<=t<=10000).
The following T-lines, two digits per line, n,q (n<=109, 1<=q<=30000)
Output Description
The file contains a T line, and each line corresponds to an answer.
Sample Input
3
6 2
7 3
7 11
Sample Output
1
0
10
data range and tips
1<=t<=10000
n<=109, 1<=q<=30000
Matrix multiplication +fibonacci:
[Fn,f (N-1)]=[f (n-1), F (n-2)]*[(a)
(1,0)] {This is the only way to write, don't hit me}
#include <cstdio>intn,p,t,b[3];Long Longa[3][3],c[3][3],d[3][3];intChintx) {c[1][1]=c[2][2]=1; c[1][2]=c[2][1]=0;//guarantee c[][] when multiplied by the first time with a[][], the value is unchanged; while(x>1) { intH= (x/2)*2; if(x!=h) { for(intI=1; i<=2; i++) for(intj=1; j<=2; j + +) for(intk=1; k<=2; k++) {d[i][j]+= (a[i][k]*c[k][j])%p;} /* Save extra a[][] to c[][], melted down fast power; for(intI=1; i<=2; i++) for(intj=1; j<=2; j + +) {c[i][j]=d[i][j];d [i][j]=0;} } for(intI=1; i<=2; i++) for(intj=1; j<=2; j + +) for(intk=1; k<=2; k++) d[i][j]+= ((a[i][k]%p) * (a[k][j]%p))%p; for(intI=1; i<=2; i++) for(intj=1; j<=2; j + +) {a[i][j]=d[i][j];d [i][j]=0;} X=x/2; } for(intI=1; i<=2; i++) for(intj=1; j<=2; j + +) for(intk=1; k<=2; k++) d[i][j]+= (A[i][k]*c[k][j])%p;//to multiply the c[][] and a[][];return(d[1][1]+d[2][1])%P;//fn=f1*d[1][1]+f0*d[2][1], which is obtained after matrix multiplication is simplified;}intMain () {scanf ("%d",&t); for(intI=1; i<=t;i++) { for(intI=1; i<=2; i++) for(intj=1; j<=2; j + +) d[i][j]=0; a[1][1]=a[1][2]=a[2][1]=1; a[2][2]=0; b[0]=1; b[1]=1; b[2]=2;//various initialization; SCANF ("%d%d",&n,&p); if(n<3) printf ("%d", b[n]%p); Else{ intAns=ch (n1); printf ("%d\n", ans); } } return 0;}
Fibonacci Sequence--matrix multiplication optimization