Hdu 3221 Brute-force Algorithm)
One night I came up with such a question .. Mark.
Given such a program, I asked how many times the funny function called.
Let's define an array as follows: f [1] = a, f [2] = B, f [3] = f [2] * f [3] ...... f [n] = f [n-1] * f [N-2]. The corresponding value can also be a ^ 1 * B ^ 0% p, a ^ 0 * B ^ 1% p, a ^ 1 * B ^ 1% p ,..... a ^ fib [n-3] * B ^ fib [N-2] % p.That is, the exponent of a and B is the same as that of fib series after n = 3.
Because n is large, fib [n] also wants to be large. A ^ fib [n] % p can use a ^ fib [n] % p = a ^ (fib [n] % phi [p] + phi [p]) % p for power reduction, where fib [n]> = phi [p]. Evaluate fib [n] % phi [p] to construct a matrix, and use the Matrix to quickly calculate fib [n] % phi [p].
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include # define LL long # define _ LL _ int64 # define eps 1e-12 # define PI acos (-1.0) # define C 240 # define S 20 using namespace std; const int maxn = 110; struct matrix {LL mat [3] [3]; void init () {memset (mat, 0, sizeof (mat )); for (int I = 0; I <2; I ++) mat [I] [I] = 1 ;}} m; LL a, B, p, n, phi_p; LL fib [10000000]; // phi [p] LL Eular (LL num) {LL res = num; for (int I = 2; I * I <= num; I ++) {if (num % I = 0) {res-= Res/I; while (num % I = 0) num/= I ;}} if (num> 1) res-= res/num; return res ;} // multiply matrix by matrix mul_matrix (matrix x, matrix y) {matrix ans; memset (ans. mat, 0, sizeof (ans. mat); for (int I = 0; I <2; I ++) {for (int k = 0; k <2; k ++) {if (x. mat [I] [k] = 0) continue; for (int j = 0; j <2; j ++) {ans. mat [I] [j] = (ans. mat [I] [j] + x. mat [I] [k] * y. mat [k] [j]) % phi_p ;}} return ans ;}// a ^ t % phi_pLL pow_matrix (LL T) {matrix a, B;. mat [0] [0] =. mat [0] [1] =. mat [1] [0] = 1;. mat [1] [1] = 0; B. init (); while (t) {if (t & 1) B = mul_matrix (a, B); a = mul_matrix (a, a); t >>= 1 ;} return B. mat [0] [0];} // a ^ t % pLL pow (LL a, LL t) {LL res = 1; a % = p; while (t) {if (t & 1) res = res * a % p; a = a * a % p; t >>=1 ;} return res ;} // a ^ fib [t] % p is converted to a ^ (fib [t] % phi [p] + phi [p]) % p, fib [t]> = phi [p]. LL solve (LL a, LL t) {fib [0] = 1; fib [1] = 1; int I; for (I = 2; I <= t; I ++) {fib [I] = fib [I-1] + fib [I-2]; if (fib [I]> = phi_p) break;} if (I <= t) // when the condition fib [t]> = phi [p] is met, the power is reduced by {LL c = pow_matrix (t) + phi_p; return pow (a, c );} else return pow (a, fib [t]);} int main () {int test; scanf (% d, & test); for (int item = 1; item <= test; item ++) {scanf (% lld, & a, & B, & p, & n ); printf (Case # % d:, item); if (n = 1) {printf (% lld, a % p); continue;} if (n = 2) {printf (% lld, B % p); continue;} if (n = 3) {printf (% lld, a * B % p); continue ;} if (p = 1) {printf (0); continue;} phi_p = Eular (p); LL res = solve (a, n-3) * solve (B, N-2) % p; printf (% lld, res);} return 0 ;}