Title Description
We all know that the Fibonacci sequence it, f1 = 1, f2 = 1, f3 = 2, f4 = 3, ..., fn = fn-1 + fn-2
Now the problem is simple, and the input n m, seeking fn mod m.
Input Format
Input n, m.
Output Format
Output fn mod m.
Sample data
Sample input
Sample Output
Limitations and Tips
To 100% of the data, 1≤n≤2 × 10 ^ 9,1≤m≤10 ^ 9 + 10
Thinking
Template title, rapid matrix multiplication power +
Code:
#include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; long long n,Mod; long long a[3][3],b[3][3]; long long ans[3][3],c[3][3]; void add(long long &x,long long y) { x=x+y; x-=(x>=Mod)?Mod:0; return; } int main () { a[1][1]=a[1][2]=a[2][1]=1; a[2][2]=0; ans[1][1]=ans[2][2]=1; ans[1][2]=ans[2][1]=0; scanf("%lld%lld",&n,&Mod); n--; while(n) { if(n&1) { memset(c,0,sizeof(c)); for(int i=1; i<=2; i++) for(int j=1; j<=2; j++) for(int k=1; k<=2;a ++) add(c[i][j],ans[i][k]*a[k][j]%Mod); memmove(ans,c,sizeof(ans)); } memset(c,0,sizeof(c)); for(int i=1; i<=2; i++) for(int j=1; j<=2; j++) for(int k=1; k<=2; k++) add(c[i][j],a[i][k]*a[k][j]%Mod); memmove(a,c,sizeof(a)); n>>=1; } b[1][1]=1; b[1][2]=0; memset(c,0,sizeof(c)); for(int i=1; i<=2; i++) for(int j=1; j<=2; j++) for(int k=1; k<=2; k++) add(c[i][j],ans[i][k]*b[k][j]); memmove(b,c,sizeof(b)); printf("%lld\n",b[1][1]); return 0; }