Problem Description
Holion August will eat every thing he has found.
Now there are many foods,but he does not want to eat all of them at once,so he find a sequence.
fn=⎧⎩⎨⎪⎪1,ab,abfcn−1fn−2,n=1n=2otherwise
He gives you 5 numbers n,a,b,c,p,and he will eat fn foods.But there are only p foods,so you should tell him fn mod p.
Now there are many foods,but he does not want to eat all of them at once,so he find a sequence.
fn=⎧⎩⎨⎪⎪1,ab,abfcn−1fn−2,n=1n=2otherwise
He gives you 5 numbers n,a,b,c,p,and he will eat fn foods.But there are only p foods,so you should tell him fn mod p.
Input
The first line has a number,T,means testcase.
Each testcase has 5 numbers,including n,a,b,c,p in a line.
1≤T≤10,1≤n≤1018,1≤a,b,c≤109 , p is a prime number,and p≤109+7 .
Each testcase has 5 numbers,including n,a,b,c,p in a line.
1≤T≤10,1≤n≤1018,1≤a,b,c≤109 , p is a prime number,and p≤109+7 .
Output
Output one number for each case,which is
fn
mod p.
Sample Input
1 5 3 3 3 233
Sample Output
190
把次数拿下来就可以用矩阵递推了,要注意会有a%p=0的情况
#pragma comment(linker, "/STACK:102400000,102400000") #include<map> #include<set> #include<cmath> #include<queue> #include<stack> #include<bitset> #include<cstdio> #include<string> #include<cstring> #include<iostream> #include<algorithm> #include<functional> using namespace std; typedef long long LL; const int low(int x) { return x&-x; } const int INF = 0x7FFFFFFF; const int mod = 1e9 + 7; const int maxn = 2e5 + 10; LL n, a, b, c, p; int T; struct martix { LL a[3][3]; }A, B; martix operator*(const martix&a, const martix&b) { martix c; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { c.a[i][j] = 0; for (int k = 0; k < 3; k++) { (c.a[i][j] += a.a[i][k] * b.a[k][j] % (p - 1)) %= (p - 1); } } } return c; } martix get(martix a, LL x) { martix c; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { c.a[i][j] = i == j; } } for (x; x; x >>= 1) { if (x & 1) c = c*a; a = a*a; } return c; } LL get(LL x, LL y) { if (n > 1 && y == 0) y = p - 1; LL ans = 1; for (y; y; y >>= 1) { if (y & 1) ans = ans*x%p; x = x*x%p; } return ans; } int main() { scanf("%d", &T); while (T--) { cin >> n >> a >> b >> c >> p; A.a[0][0] = 0; A.a[0][1] = b; A.a[0][2] = b; B.a[0][0] = 0; B.a[0][1] = 1; B.a[0][2] = 0; B.a[1][0] = 1; B.a[1][1] = c; B.a[1][2] = 0; B.a[2][0] = 0; B.a[2][1] = 1; B.a[2][2] = 1; if (n == 1) { cout << 1 << endl; continue; } B = get(B, n - 1); A = A*B; cout << get(a, A.a[0][0]) << endl; } return 0; }