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
思路
首先利用polya求出答案为:
代码
#include <cstdio>
inline int phi(int n)
{
int res=n;
for(register int i=2; i*i<=n; ++i)
{
if(!(n%i))
{
res=(res/i)*(i-1);
while(!(n%i))
{
n/=i;
}
}
}
if(n!=1)
{
res=(res/n)*(n-1);
}
return res;
}
inline int quickpow(int a,int b,int p)
{
int res=1;
while(b)
{
if(b&1)
{
res=1ll*res*a%p;
}
a=1ll*a*a%p;
b>>=1;
}
return res;
}
int t,n,p;
int main()
{
scanf("%d",&t);
while(t--)
{
int ans=0;
scanf("%d%d",&n,&p);
for(register int i=1; i*i<=n; ++i)
{
if(!(n%i))
{
ans+=1ll*phi(n/i)*quickpow(n,i-1,p)%p;
if(i*i!=n)
{
ans+=1ll*phi(i)*quickpow(n,n/i-1,p)%p;
}
ans%=p;
}
}
printf("%d\n",ans);
}
return 0;
}