For a sequence X. Xn+1 = ( a * Xn + c ) % p. Now given a, c, X0, n, p, you need to calculate Xn.
Input
The first line contains an integer T, indicating that there are T test cases (T <= 20);
For each case:
The only line of the input contains five integers a , c , X0 , n , p. ( a,c,p <= 1e9 , X0,n <= 1e18 )
Output
For each test case, output the integer Xn.
Sample Input
4 4 3 1 1 7 4 3 7 0 3 4 3 7 1 3 2018 7 15 8 31
Sample Output
0 7 1 10
矩阵快速幂
由题意构造
| a 1 |
| 0 1 |
然后矩阵快速幂一下即可
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<pair<ll,ll>,pair<ll,ll> > pll;
int T;
ll a,c,x0,n,p;
pll operator *(const pll &a,const pll &b)
{
return make_pair( make_pair((a.first.first*b.first.first%p+a.first.second*b.second.first%p)%p,
(a.first.first*b.first.second%p+a.first.second*b.second.second%p)%p),
make_pair((a.second.first*b.first.first%p+a.second.second*b.second.first%p)%p,
(a.second.first*b.first.second%p+a.second.second*b.second.second%p)%p
) );
}
ll F(ll y)
{
pll ans=make_pair(make_pair(a,1),make_pair(0,1)),
x=make_pair(make_pair(1,0),make_pair(0,1));
while(y)
{
if(y&1) x=x*ans;
ans=ans*ans;
y>>=1;
}
return x0%p*x.first.first%p+x.first.second*c%p;
}
int main()
{
cin>>T;
while(T--)
{
cin>>a>>c>>x0>>n>>p;
if(n==0) cout<<x0<<endl;
else cout<<F(n)%p<<endl;
}
return 0;
}