题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4565
代码如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
#define LL __int64
struct matrix{
LL f[2][2];
};
LL m;
matrix mul(matrix a, matrix b)
{
LL i, j, k;
matrix c;
memset(c.f, 0, sizeof(c.f));
for (i = 0; i<2; i++)
for (j = 0; j<2; j++)
for (k = 0; k<2; k++)
c.f[i][j] = (c.f[i][j] + a.f[i][k] * b.f[k][j]) % m;
return c;
}
matrix pow_mod(matrix e, LL b)
{
matrix s;
s.f[0][0] = s.f[1][1] = 1;
s.f[0][1] = s.f[1][0] = 0;
while (b)
{
if (b%2==1)
s = mul(s, e);
e = mul(e, e);
b/=2;
}
return s;
}
int main()
{
LL a, b, n;
while (scanf("%I64d%I64d%I64d%I64d", &a, &b, &n, &m)!=EOF)
// while(cin>>a>>b>>n>>m)
{
LL p, q, ans;
matrix e;
p = 2 * a;
q = a*a - b;
e.f[0][0] = p; e.f[0][1] = -q;
e.f[1][0] = 1; e.f[1][1] = 0;
e = pow_mod(e, n - 1);
ans = ((p*e.f[0][0] + 2 * e.f[0][1]) % m + m) % m;
printf("%d\n", ans);
}
return 0;
}