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
题目大意
N种颜色,N个珠子,问有多少种不同的组成方式,旋转之后相同的不计入总数。最后结果%P。
解题思路
代码实现
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define maxn 40000
bool visit[maxn];
int prime[maxn];
int n,p;
void getprime()
{
int num=0;
memset(visit,0,sizeof(visit));
for(int i=2;i<maxn;i++)
{
if(!visit[i]) prime[num++]=i;
for(int j=0;j<num&&i*prime[j]<maxn;j++)
{
visit[i*prime[j]]=true;
if(i%prime[j]==0)
break;
}
}
}
int cal(int N)
{
int ans=N,t=N;
for(int i=0; prime[i]*prime[i]<=N; i++)
{
if(t%prime[i]==0)
{
while(t%prime[i]==0)
t/=prime[i];
ans=ans-ans/prime[i];
}
}
if(t>1)
ans=ans-ans/t;
return ans;
}
int multi(int a,int b)
{
int ans=1;
while(b>0)
{
if(b%2==1)
ans=(ans%p)*(a%p)%p;
a=a*a%p;
b/=2;
}
return ans;
}
int main()
{
int T;
getprime();
scanf("%d",&T);
while(T--)
{
int euler1,euler2,ans=0;
scanf("%d %d",&n,&p);
for(int i=1; i*i<=n; i++)
{
if(n%i==0)
{
euler1=cal(n/i)%p;
ans=(ans+(multi(n%p,i-1)%p*euler1)%p)%p; //减1是为了先约去最后结果需要除的n
if(i*i!=n)
{
euler2=cal(i)%p;
ans=(ans+(multi(n%p,n/i-1)%p*euler2)%p)%p; //同上
}
}
}
printf("%d\n",ans);
}
return 0;
}