题意:
然后求fn取p的余之后的答案,n 为10^18次方;
思路: 设xn为a的幂: 则可以得出xn = c * x(n -1) + x(n - 2) + b;
由费马小定理可以得出,fn %= p, 那么xn %= (mod - 1);
矩阵为: c b 1
1 0 0
0 0 1
#include <iostream>
#include <set>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,p;
struct Matrix
{
Matrix()
{
memset(maze,0,sizeof(maze));
for(int i = 0; i < 3; i ++)
maze[i][i] = 1;
}
Matrix(ll c,ll b)
{
maze[0][1] = maze[1][0] = maze[2][2] = 1;
maze[0][0] = c;
maze[0][2] = b;
maze[1][1] = maze[1][2] = maze[2][0] = maze[2][1] = 0;
}
void show()
{
for(int i = 0; i < 3; i ++)
{
for(int j = 0; j < 3; j ++)
{
cout << maze[i][j] << " ";
}
cout << endl;
}
}
ll maze[3][3];
inline Matrix operator *(const Matrix& b)
{
Matrix c;
for(int i = 0; i < 3; i ++)
{
for(int j = 0; j < 3; j ++)
{
c.maze[i][j] = 0;
for(int k = 0; k < 3; k ++)
{
c.maze[i][j] += (maze[i][k] * b.maze[k][j]) % (p - 1);
c.maze[i][j] %= (p - 1);
}
}
}
return c;
}
};
ll a,b,c;
Matrix pow(ll len)
{
// cout << "Pass _ by" << endl;
// cout << len << endl;
Matrix ans;
// ans.show();
Matrix t(c,b);
while(len)
{
if(len & 1)
ans = ans * t;
len >>= 1;
t = t * t;
}
return ans;
}
ll pows(ll x,ll n)
{
ll ans = 1;
ll t = x;
while(n)
{
if(n & 1)
ans = ans * t % p;
n >>= 1;
t = (t * t) % p;
}
return ans;
}
ll solve()
{
if(n == 1)
return 1;
if(n == 2)
return pow(a,b);
Matrix temp = pow(n - 2);
ll ans = temp.maze[0][0] * b + temp.maze[0][2];
ans = pows(a,ans);
return ans;
}
int main()
{
int Tcase;
scanf("%d",&Tcase);
while(Tcase --)
{
scanf("%I64d%I64d%I64d%I64d%I64d",&n,&a,&b,&c,&p);
cout << solve() << endl;
}
return 0;
}