Reading comprehension
Read the program below carefully then answer the question.
#pragma comment(linker, “/STACK:1024000000,1024000000”)
#include
#include
#include
#include
#include
#include
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=(ans2+1)%m;
else ans=ans2%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
大致题意:阅读这段程序,求f(n)%m的值
思路:n,m均很大,因此想到了矩阵快速幂(方法貌似不唯一,我构造了一个2*2的初始矩阵,第一行第一列表示第一个值,第二行第一列表示第二个值)
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
struct matrix
{
ll x[105][105];
ll n, m;
matrix(){memset(x, 0, sizeof(x));}
};
ll n, m;
matrix multiply(matrix &a, matrix &b)
{
matrix c;
c.n = a.n, c.m = b.m;
for(int i = 1; i <= a.n; i++){
for(int j = 1; j <= a.m; j++){
for(int k = 1; k <= a.m; k++){
c.x[i][j] += a.x[i][k]*b.x[k][j];
}
c.x[i][j] %= m;
}
}
return c;
}
matrix mpow(matrix &a, ll m)
{
matrix change;
change.n = 2;
change.m = 2;
change.x[1][1] = 4;
change.x[1][2] = 0;
change.x[2][1] = 1;
change.x[2][2] = 1;
while(m > 0){
if(m & 1)a = multiply(a, change);
change = multiply(change, change);
m >>= 1;
}
return a;
}
int main()
{
while(~scanf("%lld%lld", &n, &m)){
matrix a;
a.n = a.m = 2;
a.x[1][1] = 1;
a.x[1][2] = 1;
a.x[2][1] = 2;
a.x[2][2] = 2;
if(n == 1){
printf("%lld\n", n % m);
continue;
}
else if(n == 2){
printf("%lld\n", 2 % m);
continue;
}
matrix res;
res = mpow(a, (n - 1)/2);
if(n & 1){
printf("%lld\n", res.x[1][1] % m);
}else{
printf("%lld\n", res.x[2][1] % m);
}
}
return 0;
}