题目链接:
POJ 2154 Color
题意:
n
个颜色涂
分析:
根据
Polya
原理可得
Ans=∑i=1nngcd(n,i)=∑d=1d=nnd∑i=1i=n[gcd(n,i)==d]=∑d=1nnd∑i=1n[gcd(nd,id)==1]=∑d=1nnd∗ϕ(nd)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#include <bitset>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 100010;
int prime_cnt, prime[MAX_N];
bitset<MAX_N> bs;
void GetPrime()
{
prime_cnt = 0;
bs.set();
for(int i = 2; i < MAX_N; ++i) {
if(bs[i]) prime[prime_cnt++] = i;
for(int j = 0; j < prime_cnt && i * prime[j] < MAX_N; ++j) {
bs[i * prime[j]] = 0;
if(i % prime[j] == 0) break;
}
}
}
int GetPhi(int x)
{
int res = x;
for(int i = 0; prime[i] * prime[i] <= x; ++i) {
if(x % prime[i] == 0){
res = res / prime[i] * (prime[i] - 1);
x /= prime[i];
while(x % prime[i] == 0){
x /= prime[i];
}
}
}
if(x > 1) res = res / x * (x - 1);
return res;
}
ll quick_pow(ll x, ll y, ll mod)
{
ll res = 1, tmp = x;
while(y) {
if(y & 1) res = res * tmp % mod;
tmp = tmp * tmp % mod;
y >>= 1;
}
return res;
}
int main()
{
GetPrime();
int T, n, mod;
scanf("%d", &T);
while(T--) {
scanf("%d%d", &n, &mod);
ll ans = 0;
for(int i = 1; i * i <= n; ++i) {
if(n % i == 0) {
ans = (ans + quick_pow(n, i - 1, mod) * GetPhi(n / i) % mod) % mod;
if(n / i != i) {
ans = (ans + quick_pow(n, n / i - 1, mod) * GetPhi(i) % mod) % mod;
}
}
}
printf("%lld\n", ans);
}
return 0;
}