uva10692-指数循环节

来源:互联网 发布:火影忍者手办淘宝 编辑:程序博客网 时间:2024/05/16 10:26

题目链接:https://vjudge.net/problem/UVA-10692


求 a1 ^ (a2 ^ (a3 ^ (... ^ an) )) % m 的值


利用指数循环节的降幂公式 a ^ b % mod = a ^ (b ^ phi(mod) + phi(mod)) % mod 递归的进行计算即可,phi()为欧拉函数,可以预处理出来


代码:


# include <iostream># include <algorithm># include <cstdio># include <cstring># include <cmath>using namespace std;typedef long long LL;const int maxn = 10 + 5;const int maxm = 1e4 + 5;char s[maxn];int a[maxn];int phi[maxm];int m, n;int fast_pow(int x, int n, int mod) {    int r = 1;    while (n) {        if (n & 1) r = (LL)r * x % mod;        x = (LL)x * x % mod;        n >>= 1;    }    return r;}void phi_table() {    memset(phi, 0, sizeof phi);    phi[1] = 1;    for (int i = 2; i < maxm; ++i) if (!phi[i])        for (int j = i; j < maxm; j += i) {            if (!phi[j]) phi[j] = j;            phi[j] = phi[j] / i * (i - 1);        }}int solve(int id, int mod) {    if (id == n - 1) return a[id] % mod;    else return fast_pow(a[id], solve(id + 1, phi[mod]) + phi[mod], mod) % mod;}int main(void){    phi_table();    int Case = 0;    while (scanf("%s", s) == 1 && strcmp(s, "#")) {        sscanf(s, "%d", &m);        scanf("%d", &n);        for (int i = 0; i < n; ++i) scanf("%d", a + i);        printf("Case #%d: %d\n", ++Case, solve(0, m));    }    return 0;}/*10 4 2 3 4 5100 2 5 253 3 2 3 2#*/


原创粉丝点击