Codevs 1250 Fibonacci Seriestime limit: 1 sspace limit: 128000 KBtitle level: Diamonds DiamondTitle 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<=109, 1<=q<=30000)
Output description
Output Description
The file contains a T line, and each line corresponds to an answer.
Sample input
Sample Input
3
6 2
9}
7 11
Sample output
Sample Output
1
0
10
Data range and Tips
Data Size & Hint
1<=t<=10000
n<=109, 1<=q<=30000
Category labels
Tags Click here to expandMatrix multiplication Number Theory
1 #defineN 32#include <iostream>3 using namespacestd;4#include <cstdio>5#include <cstring>6 structjz{7 intCal,line;8 intJz[n][n];9 };Ten intQ; One intRead () A { - Chars; - intans=0, ff=1; thes=GetChar (); - while(s<'0'|| S>'9') - { - if(s=='-') ff=-1; +s=GetChar (); - } + while('0'<=s&&s<='9') A { atans=ans*Ten+s-'0'; -s=GetChar (); - } - returnans*ff; - } - Jz martax (Jz x,jz y) in { - Jz ans; toAns.line=X.line; +Ans.cal=y.cal; - for(intI=1; i<=ans.line;++i) the for(intj=1; j<=ans.cal;++j) * { $ans.jz[i][j]=0;Panax Notoginseng for(intk=1; k<=x.cal;++k) -Ans.jz[i][j]= (Ans.jz[i][j]+x.jz[i][k]*y.jz[k][j])%Q; the } + returnans; A } the intFast_martax (intN) + { - if(n==0|| n==1)return 1; $n--; $ Jz ans,a; -A.cal=a.line=2; -a.jz[1][1]=0; a.jz[1][2]=1; thea.jz[2][1]=1; a.jz[2][2]=1; -Ans.line=2; ans.cal=1;Wuyians.jz[1][1]=1; ans.jz[2][1]=1; the while(n) - { Wu if(n&1) - { Aboutans=Martax (A,ans); $ } -n>>=1; -A=Martax (a,a); - } A returnans.jz[2][1]%Q; + } the intMain () - { $ intT,n; thet=read (); the while(t--) the { theN=read (); q=read (); -printf"%d\n", Fast_martax (n)); in } the return 0; the}
Matrix multiplication Fast Power Codevs 1250 Fibonacci sequence