FZU - 1759 Problem 1759 Super A^B mod C 【质数循环节 + 欧拉函数】

Problem 1759 Super A^B mod C

Accept: 1326 Submit: 4496
Time Limit: 1000 mSec Memory Limit : 32768 KB

Problem Description

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

Source

FZU 2009 Summer Training IV–Number Theory

题意: 计算 a b % c

分析: 由于b很大,这里必须要降幂计算,如下:

a b % c = a b % φ ( c ) + φ ( c ) % c
其中 φ ( c ) 为,c的欧拉值,也就是小于c,且于c互质的数,详细参考这里

参考代码

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;

typedef long long ll;

const int maxn = 1e6 + 10;

char s[maxn];


ll euler(ll x) {
    ll m = (ll) sqrt(x + 0.5);
    ll res = x;
    for (int i = 2; i <= m; i++) {
        if (x % i == 0) {
            res = res / i * (i - 1);
            while (x % i == 0) x /= i;
        }
    }
    if (x != 1) res = res / x * (x - 1);
    return res;
}

ll qpow(ll a, ll b, ll p) {
    ll res = 1;
    while (b) {
        if (b & 1) res = (res * a) % p;
        a = (a * a) % p;
        b >>= 1;
    }
    return res;
}

int main() {
    ll a,c;
    while (~scanf("%I64d %s %I64d", &a, s, &c)) {
        ll cc = euler(c);
        int len = strlen(s);
        ll t = 0;
        for (int i = 0; i < len; i++) {
            t = (t * 10 + s[i] - '0') % cc;
        }
        t = (t + c) % c;
        printf("%I64d\n", qpow(a, t, c));
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/nobleman__/article/details/80078040
今日推荐