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.
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
题目大意:给定 N 种颜色珠子,每种颜色的珠子的个数不限,将这些做成长度为 N 且不重复的项链 ( 只考虑旋转,不考虑翻转 ) ,并对所得结果 mod p。
题解:Polya计数。
与 POJ2409 差不多。但一看数据范围,就不是这么回事了,2409 完全可以直接循环处理,但这题目 n 最大达 100000000,显然会 TLE,故需寻求更佳的解决方案。
于是用 欧拉函数 进行优化。
附代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define MAXN 50010
using namespace std;
int n,p,k=0,prime[MAXN];
inline int read(){
int date=0,w=1;char c=0;
while(c<'0'||c>'9'){if(c=='-')w=-1;c=getchar();}
while(c>='0'&&c<='9'){date=date*10+c-'0';c=getchar();}
return date*w;
}
void make(){
int x=MAXN-10;
bool np[MAXN*2];
memset(np,0,sizeof(np));
for(int i=2;i<=x;i++){
if(!np[i])prime[++k]=i;
for(int j=1;j<=k&&prime[j]*i<=x;j++){
np[prime[j]*i]=true;
if(i%prime[j]==0)break;
}
}
}
long long euler(int x){
long long s=1;
for(int i=1;prime[i]*prime[i]<=x;i++){
if(x%prime[i]!=0)continue;
s*=prime[i]-1;
x/=prime[i];
while(x%prime[i]==0){
s*=prime[i];
x/=prime[i];
}
}
if(x>1)s*=x-1;
return s%p;
}
long long mexp(long long a,long long b,long long c){
long long s=1;
while(b){
if(b&1)s=s%c*a%c;
a=a%c*a%c;
b>>=1;
}
return s%c;
}
int main(){
int t=read();
make();
while(t--){
n=read();p=read();
long long ans=0;
for(int i=1;i*i<=n;i++){
if(i*i==n)ans=(ans+mexp(n,i-1,p)*euler(i)%p)%p;
else if(n%i==0)ans=(ans+mexp(n,n/i-1,p)*euler(i)%p+mexp(n,i-1,p)*euler(n/i)%p)%p;
}
printf("%lld\n",ans);
}
return 0;
}