FZU Super A ^ B mod C
Super A ^ B mod C
Given A, B, C, You shoshould quickly calculate the result of A ^ B mod C. (1 <= A, C <= 000000000,1 <= B <= 10 ^ 1000000 ).
There are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.
Output
For each testcase, output an integer, denotes the result of A ^ B mod C.
Sample Input
3 2 42 10 1000
Sample Output
124
Algorithm analysis:
The Euler function is worthy of an application. That is, A ^ B % C = A ^ (B % (euler_phi (C) % C * A ^ euler_phi (C ).
I don't know how to exit this theorem. If you are interested, you can use Baidu. Why is the equation true?> 〉?
Because we will find a rule. When A ^ B % C, A loop section appears after A certain number. The summary will find that this cycle section is exactly euler_phi (C ). Therefore, as long as we take the remainder Euler's value at most B, we will have to make the data less than 10 ^ 9. At this time, we can solve it with a common approach.
If C is a prime number, it is a special case. We can know from the ferma's theorem that, at this timeA ^ B % C = A ^ (B % (C-1) % CI used java to write CE... later I was helpless but I could only simulate it with brute force.
#include
#include #include
#include
#include
#include
#include
#include
#include
using namespace std;typedef long long LL;typedef pair
P;inline int read(){ int x = 0,f = 1; char ch = getchar(); while(ch < '0'||ch > '9'){if(ch == '-')f=-1;ch = getchar();} while(ch >= '0'&&ch <= '9'){x = x * 10 + ch -'0';ch = getchar();} return x*f;}//////////////////////////////////////////////////////////////////LL A,C;char B[1000005];LL euler_phi(LL n){ int m = sqrt(n + 0.5); LL ans = n; for(int i = 2;i <= m;++i)if(0 == n % i){ ans = ans / i * (i-1); while(0 == n % i) n /= i; } if(n > 1) ans = ans / n * (n-1); return ans;}LL getMod(char *str,LL m){ LL res = 0; int len = strlen(str); for(int i = 0;i < len;){ while(res < C&&i < len){ res = res * 10 + (str[i] - '0'); ++i; } //cout << "res: " << res << endl; res %= m; } return res;}LL powMod(LL a,LL b,LL mod){ LL res = 1; a %= mod; while(b > 0){ if(b & 1) res = res * a % mod; a = a * a % mod; b >>= 1; } return res % mod;}int main(){ while(~scanf("%lld%s%lld",&A,B,&C)){ LL phi = euler_phi(C); LL mod = getMod(B,phi); // cout <<"phi: " << phi << " " << mod << endl;// LL tmp1 = powMod(A,phi,C); // cout << "A: " << A << " C: " << C << endl;// LL tmp2 = powMod(A,mod,C); // cout << "tmp1: " << tmp1 << " tmp2: " << tmp2 << endl; printf("%lld\n",powMod(A,phi,C) * powMod(A,mod,C) % C); } return 0;}/*3 2 42 10 1000*/