Read the program below carefully then answer the question.
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include<iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include<vector>
const int MAX=100000*2;
const int INF=1e9;
int main()
{
int n,m,ans,i;
while(scanf("%d%d",&n,&m)!=EOF)
{
ans=0;
for(i=1;i<=n;i++)
{
if(i&1)ans=(ans*2+1)%m;
else ans=ans*2%m;
}
printf("%d\n",ans);
}
return 0;
}
Input
Multi test cases,each line will contain two integers n and m. Process to end of file.
[Technical Specification]
1<=n, m <= 1000000000
Output
For each case,output an integer,represents the output of above program.
Sample Input
1 10
3 100
Sample Output
1
5
题意:当n为奇数时,f[n] = 2*f[n-1]+1,f[n-1] = 2*f[n-2],所以:f[n] = f[n-1] + 2*f[n-2] + 1;
当n为偶数时,f[n] = 2*f[n-1],f[n-1] = 2*f[n-2] + 1,所以:f[n] = f[n-1] + 2*f[n-2] + 1;
综上:f[n] = f[n-1] + 2*f[n-2] + 1,构造矩阵:
利用矩阵快速幂求f(n)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
typedef long long LL;
LL MOD;
const int Size = 3;
struct MA
{
LL mat[Size][Size];
};
MA mul(MA x, MA y)
{
MA ret;
memset(ret.mat, 0, sizeof(ret.mat));
for(int i = 0; i<Size; i++)
for(int j = 0; j<Size; j++)
for(int k = 0; k<Size; k++)
{
ret.mat[i][j] += (1LL*x.mat[i][k]*y.mat[k][j])%MOD;
ret.mat[i][j] %= MOD;
}
return ret;
}
MA qpow(MA x, LL y)
{
MA s;
memset(s.mat,0,sizeof(s.mat));
for(int i=0;i<Size;i++) s.mat[i][i] = 1;
while(y)
{
if(y&1) s = mul(s, x);
x = mul(x, x);
y >>= 1;
}
return s;
}
MA tmp = {
1, 2, 1,
1, 0, 0,
0, 0, 1
};
int main()
{
LL n, m;
while(~scanf("%lld%lld",&n,&m))
{
MOD = m;
if(n<=2)
{
printf("%lld\n", n%MOD);
continue;
}
MA s = tmp;
s = qpow(s, n-2);
LL ans = ((2LL*s.mat[0][0]%MOD + s.mat[0][1])%MOD+s.mat[0][2])%MOD;
printf("%lld\n", ans);
}
}