UVa 10692 - Huge Mods

链接

传送门

题意

给出\(m\)\(n\)个数字\(a_i\),求\(a_1\)\(a_2\)\(\cdot \cdot \cdot\)^\(a_n % m\)的值。

思路

利用欧拉定理进行解决。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

typedef long long LL;
const int maxn = 12;
const int maxm = 10010;
char s[maxn];
int a[maxn];
int phi[maxm];

void phi_table() {
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 pow_mod(int x, int k, int mod) {
if (x == 1 || k == 0) {
return 1;
}
int res = 1;
for (int i = 0; i < k; ++i) {
res *= x;
if (res >= mod) {
break;
}
}
if (res < mod) {
return res;
}
res = 1;
int cur = x;
while (k) {
if (k & 1) {
res = res * cur % mod;
}
cur = cur * cur % mod;
k >>= 1;
}
return res + mod;
}

int dfs(int d, int mod, int n) {
if (d == n) {
return a[d] >= mod ? a[d] % mod + mod : a[d];
}
return pow_mod(a[d], dfs(d + 1, phi[mod], n), mod);
}

int main() {
phi_table();
int t = 0;
while (~scanf("%s", s) && s[0] != '#') {
int n, m;
sscanf(s, "%d", &m);
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
}
printf("Case #%d: %d\n", ++t, dfs(1, m, n) % m);
}
return 0;
}