置换群,burnside引理的题目。

这道题代表了一类题目的优化

裸的算法是 ∑n^(gcd(n,i)) 1<i<=n

复杂度过高,进行优化。

置换群种循环的个数L = n / gcd(n, i)

因为如果L | n, 则有n / L | n

则环的长度L的范围是1 ~ sqrt(L)

令a = gcd(n, i), 设i = at

则只有i与t互质的时候,gcd(i, t) = a

则最后可以优化为 ∑(Φ(i) * n ^ (i)) % p

###Code

POJ 2154
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
76
77
78
79
//By Brickgao
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <vector>
using namespace std;
#define out(v) cerr << #v << ": " << (v) << endl
#define SZ(v) ((int)(v).size())
#define LL long long
const int maxint = -1u>>1;
template <class T> bool get_max(T& a, const T &b) {return b > a? a = b, 1: 0;}
template <class T> bool get_min(T& a, const T &b) {return b < a? a = b, 1: 0;}

long long ans;
int t, num, n, p;
int isprime[50001];
int prime[8001];

void getprime() {
num = 0;
for(int i = 2; i <= 50000; i ++) {
if(!isprime[i]) {
prime[num ++] = i;
for(int j = 1; j * i <= 50000; j ++) {
isprime[i * j] = 1;
}
}
}
}

int euler(int x) {
int res = x;
for(int i = 0; i < num && prime[i] * prime[i] <= x; i++) {
if(x % prime[i] == 0) {
res = res / prime[i] * (prime[i] - 1);
while(x % prime[i] == 0) {
x /= prime[i];
}
}
}
if(x > 1) res = res / x * (x - 1);
return res;
}

LL quickpow(LL m , LL n , LL k) {
LL tmp = 1;
m %= k;
while(n) {
if(n & 1)
tmp = (tmp * m) % k;
m = (m * m) % k;
n >>= 1;
}
return tmp;
}

int main() {
getprime();
scanf("%d", &t);
while(t --) {
ans = 0;
scanf("%d%d", &n, &p);
for(int i = 1; i < sqrt(n); i ++) {
if(n % i == 0) {
ans = (ans + euler(i) % p * quickpow(n, n / i - 1, p) + euler(n / i) % p * quickpow(n, i - 1, p)) % p;
//cout << quickpow(n,n-1,p) << " " << quickpow(n, n / i - 1, p) << " " << euler(i) << " " << euler(n / i) << endl;
}
}
if((int)sqrt(n) * (int)sqrt(n) == n) {
ans = (ans + quickpow(n, sqrt(n) - 1, p) * (euler(sqrt(n)) % p)) % p;
}
ans %= p;
cout << ans << endl;
}
return 0;
}