1303. 斐波那契前 n 项和
\[f_n = f_{n-1}+f_{n-2}
\\
S_n=S_{n-1}+f_n
\\
[f_n,f_{n-1},S_n]=
[f_{n-1},f_{n-2},S_{n-1}]
\begin{bmatrix}
1 & 1 & 1\\
1 & 0 & 1\\
0 & 0 & 1
\end{bmatrix}
=[f_1,f_0,S_1]
\begin{bmatrix}
1 & 1 \\
1 & 0
\end{bmatrix}^{n-1}
\]
const int N=3;
int n,mod;
void mul(int f[],int m[][N])
{
int c[N]={0};
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
c[i]=(c[i]+(LL)f[j]*m[j][i])%mod;
memcpy(f,c,sizeof c);
}
void mulself(int m[][N])
{
int c[N][N]={0};
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
for(int k=0;k<N;k++)
c[i][j]=(c[i][j]+(LL)m[i][k]*m[k][j])%mod;
memcpy(m,c,sizeof c);
}
int main()
{
int f[N]={1,0,1};
int m[N][N]={{1,1,1},
{1,0,1},
{0,0,1}};
cin>>n>>mod;
if(n == 1)
cout<<f[0]<<endl;
else
{
n--;
while(n)
{
if(n & 1) mul(f,m);
mulself(m);
n>>=1;
}
cout<<f[2]<<endl;
}
//system("pause");
return 0;
}