POJ - 2154 Color(Polya定理+欧拉函数)

 

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很大,直接循环会超时,根据公式,我们可以转化为求1···n,这n个数中有多少个不同的gcd,以及每个gcd的个数。也就是求每个gcd的欧拉函数。)
(Polya定理的裸题,只是加了欧拉函数的优化。)

#include <cstdio>
#include <iostream>
#define LL long long
using namespace std;
int euler(int x)
{
	int a=x,res=x;
	for(int i=2;i*i<=a;i++)
	{
		if(a%i==0)
		{
	        res=res/i*(i-1);
			while(a%i==0)
				a/=i;							
		} 
	}
	if(a>1)
	  res=res/a*(a-1);
	return res;
}
LL qsm(LL a,LL k,LL mod)
{
	LL ans=1;
	while(k)
	{
		if(k&1) ans=(ans*a)%mod;
		a=(a*a)%mod;
		k>>=1;	
	}
	return ans;
}
int main(void)
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n,p,ans=0;
		scanf("%d%d",&n,&p);
		for(int i=1;i*i<=n;i++)
		{
			if(n%i==0)
			{
				//cout<<i<<" "<<euler(i)<<endl;
				if(i*i==n)  ans=(ans+euler(i)*qsm(n,i-1,p)%p)%p;
				else ans=(ans+euler(i)*qsm(n,n/i-1,p)%p+euler(n/i)*qsm(n,i-1,p)%p)%p;					
			}

		}
		 printf("%d\n",ans);
			
	}
	
	
	
	return 0;
}
 
posted @ 2019-03-18 18:50  鸟人呀  阅读(136)  评论(0编辑  收藏  举报