Sample Input
1
5 3 3 3 233
Sample Output
190
题解:
根据递推式可以发现,答案是以a为底数的一个值,所以对指数部分做快速幂得到k,最后答案就是qpow(a,k)%mod
根据递推式易得构造矩阵
fn c 1 b fn-1
fn-1 = 1 0 0 * fn-2
1 0 0 1 1
注意点,由于是对指数进行快速幂,根据费马小定理,
如果质数p,和满足gcd(a,p) == 1的任意数字a,那么就一定满足下面的式子:
所以
对于矩阵快速幂部分部分模p-1
对于快速幂部分模p(我就这在中招了,wa了好几发)
AC:代码
#include<bits/stdc++.h>
using namespace std;
#define mp make_pair
#define ss second
#define ff first
#define pb push_back
template <class T>
void read(T &x);
template<class T, class... U> void read(T &head, U &... tail)
{
read(head), read(tail...);
}
typedef long long ll;
typedef unsigned long long ull;
typedef pair<pair<ll, ll>, pair<ll, ll> > pll;
const int inf = 0x3f3f3f3f;
const int maxn = 1e3 + 5;
ll n, a, b, c, mod,p;
struct matrix
{
ll a[3][3];
matrix()
{
memset(a, 0, sizeof a);
}
};
matrix operator *(const matrix &x, const matrix &y) //矩阵相乘函数
{
matrix res;
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
{
for(int k = 0; k < 3; k++)
{
res.a[i][j] += x.a[i][k] * y.a[k][j];
res.a[i][j] %= mod;
}
}
return res;
}
ll ksm(matrix base, ll n)
{
matrix ans;
for(int i = 0; i < 3; i++) ans.a[i][i] = 1;
while(n)
{
if(n & 1) ans = ans * base;
base = base * base;
n >>= 1;
}
return ans.a[0][0]*b + ans.a[0][2];
}
ll qpow(ll base, ll n)
{
ll ans = 1;
while(n)
{
if(n & 1) ans = ans * base % p;
base = base * base % p;
n >>= 1;
}
return ans%p;
}
void work()
{
read(n, a, b, c, p);
mod=p-1;
matrix base;
base.a[0][0] = c;base.a[0][1] = 1;base.a[0][2] = b;
base.a[1][0] = 1;base.a[2][2] = 1;
cout<<qpow(a,ksm(base,n-2))<<endl;
}
int main(int argc, char const *argv[])
{
int T;read(T);while(T--)
work();
return 0;
}
template <class T>
void read(T &x)
{
static char ch;
bool neg = false;
while(!isdigit(ch = getchar())) (ch == '-') && (neg = true);
for(x = ch - '0'; isdigit(ch = getchar()); x = x * 10 + ch - '0');
(neg) &&(x = -x);
}