Day7 - B - Super A^B mod C FZU - 1759

Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,C<=1000000000,1<=B<=10^1000000).

Input

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 4
2 10 1000

Sample Output

1
24

思路:欧拉降幂板子
typedef long long LL;

LL A, C;
char B[10000005];

LL getEuler(LL x) {
    LL ans = x;
    for(LL i = 2; i*i <= x; ++i) {
        if(x % i == 0) {
            ans = ans / i * (i-1);
            while(x % i == 0) x /= i;
        }
    }
    if(x > 1) ans = ans / x * (x-1);
    return ans;
}

LL quickPow(LL a, LL b, LL p) {  // a^b (modp)
    LL ret = 1;
    while(b) {
        if(b & 1) ret = (ret * a) % p;
        a = (a * a) % p;
        b >>= 1; 
    }
    return ret;
}


int main() {
    ios::sync_with_stdio(false), cin.tie(NULL);
    while(cin >> A >> B >> C) {
        LL phi = getEuler(C);
        LL num = 0;
        int len = strlen(B);
        for(int i = 0; i < len; ++i) {
            num = (num * 10 + B[i] - '0');
            if(num >= phi) break;
        }
        if(num >= phi) {
            num = 0;
            for(int i = 0; i < len; ++i)
                num = (num * 10 + B[i] - '0') % phi;
            cout << quickPow(A, num+phi, C) << "\n";
        } else {
            cout << quickPow(A, num, C) << "\n";
        }
    }
    
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/GRedComeT/p/12218707.html