CodeForces Gym101550E Exponial

Problem: F(n)=nF(n1)modm

Idea: 欧拉定理降幂公式: abmodp=aϕp+bmodϕpmodp(bϕp)

Code:

#include
using namespace std;

#define fi first
#define se second
#define pb push_back
#define CLR(A, X) memset(A, X, sizeof(A))
#define bitcount(X) __builtin_popcountll(X)
typedef long long LL;
typedef pair<int, int> PII;
const double eps = 1e-10;
const double PI = acos(-1.0);
const auto INF = 0x3f3f3f3f;
int dcmp(double x) { if(fabs(x) < eps) return 0; return x<0?-1:1; }

LL qpow(LL a, LL b, LL M) {
    LL ret = 1;
    while(b) {
        if(b & 1) ret = ret*a%M;
        a = a*a%M;
        b >>= 1;
    }
    return ret;
}

LL phi(LL n) {
    LL ret = n;
    for(LL i = 2; i*i <= n; i++) {
        if(n%i) continue;
        while(n%i == 0) n /= i;
        ret = ret/i*(i-1);
    }
    if(n != 1) ret = ret/n*(n-1);
    return ret;
}

LL F(LL n, LL m) {
    if(m == 1) return 0;
    if(n == 1) return 1%m;
    if(n == 2) return 2%m;
    if(n == 3) return 9%m;
    if(n == 4) return 262144%m;
    LL p = phi(m);
    return qpow(n, p+F(n-1, p), m);
}

int main() {
    LL n, m;
    scanf("%lld%lld", &n, &m);
    printf("%lld\n", F(n, m));
    return 0;
}

你可能感兴趣的:(数论-降幂公式)