http://www.elijahqi.win/archives/3405
Description
Beads of N colors are connected together into a circular necklace of N beads (N<=1000000000). Your job is to calculate how many different kinds of the necklace can be produced. You should know that the necklace might not use up all the N colors, and the repetitions that are produced by rotation around the center of the circular necklace are all neglected.
You only need to output the answer module a given number P.
Input
The first line of the input is an integer X (X <= 3500) representing the number of test cases. The following X lines each contains two numbers N and P (1 <= N <= 1000000000, 1 <= P <= 30000), representing a test case.
Output
For each test case, output one line containing the answer.
Sample Input
5
1 30000
2 30000
3 30000
4 30000
5 30000
Sample Output
1
3
11
70
629
Source
POJ Monthly,Lou Tiancheng
不考虑翻转仅仅考虑旋转同构
那么算出欧拉函数可以在sqrt的时间内解决 另外这题取模了 因此不可以把答案都算出来之后整体/n 应该在计算的时候算n^(n-1)即可
#include<cstdio>
#include<cctype>
#include<algorithm>
#define ll long long
using namespace std;
inline char gc(){
static char now[1<<16],*S,*T;
if(T==S){T=(S=now)+fread(now,1,1<<16,stdin);if (T==S) return EOF;}
return *S++;
}
inline int read(){
int x=0,f=1;char ch=gc();
while(!isdigit(ch)) {if (ch=='-') f=-1;ch=gc();}
while(isdigit(ch)) x=x*10+ch-'0',ch=gc();
return x*f;
}
const int N=1e5+10;
int phi[N],prime[N],T,n,mod,tot;bool not_prime[N];
inline int ksm(int b,int t){static int tmp;b%=mod;
for (tmp=1;t;b=b*b%mod,t>>=1) if (t&1) tmp=tmp*b%mod;return tmp;
}
inline void init(){phi[1]=1;
for (int i=2;i<=1e5;++i){
if (!not_prime[i]) prime[++tot]=i,phi[i]=i-1;
for (int j=1;prime[j]*i<=1e5;++j){
not_prime[prime[j]*i]=1;
if (i%prime[j]==0){
phi[prime[j]*i]=phi[i]*prime[j];break;
}else phi[prime[j]*i]=phi[i]*phi[prime[j]];
}
}
}
inline int calc(int x){
if (x<=1e5) return phi[x]%mod;
int now=x;
for (int j=1;prime[j]*prime[j]<=x;++j){
if (x%prime[j]) continue;now-=now/prime[j];
while(x%prime[j]==0) x/=prime[j];
}if (x>1) now-=now/x;
return now%mod;
}
inline int inc(int x,int v){return x+v>=mod?x+v-mod:x+v;}
int main(){
freopen("poj2154.in","r",stdin);
T=read();init();
while(T--){
n=read();mod=read();int ans=0;
for (int i=1;i*i<=n;++i){
if (n%i) continue;
ans=inc(ans,calc(i)*ksm(n,n/i-1)%mod);
if (ans<0) {printf("%d\n",i);break;}
if (i*i==n) continue;
ans=inc(ans,calc(n/i)*ksm(n,i-1)%mod);
}printf("%d\n",ans);
}
return 0;
}