[POJ2154]Color

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.

现在有N种颜色的珠子,我们要做一个N个珠子组成的环形项链(N≤1000000000)。
你的任务是计算可以生产多少种不同的项链。注意项链并不一定要用到所有颜色的珠子,而且旋转之后等同的项链被认为是一样的。
只需要输出这个总数Mod 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


polya+数论
考虑到polya朴素式子\(\sum\limits_{i=1}^{n} c^{gcd(i,n)}\)(c为颜色数),n到了1e9之后必定超时……
我们换个想法,考虑枚举n的每个因数d,那么\(gcd(n,i)=d\)的数共有多少个呢?共\(\phi(\frac{n}{i})\)
为什么是这么多呢?
\(gcd(x,n)=i\),则有\(gcd(\frac{x}{i},\frac{n}{i})=1\),所以说有多少个小于等于n的x满足\(gcd(\frac{x}{i},\frac{n}{i})=1\),即满足\(gcd(x,n)=i\),因此,它们的个数为\(\phi(\frac{n}{i})\)
有了这个,我们就可以得到$$Ans=\sum_{d|n} n^d*\phi(\frac{n}{d})$$
最后总状态还要除上一个n,还要对p取模,这个很简单,写个高精度。每个\(\sum\)提个n出来就好了啊

\[Ans=\sum_{d|n} n^{d-1}*\phi(\frac{n}{d}) \]

/*program from Wolfycz*/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline int read(){
	int x=0,f=1;char ch=getchar();
	for (;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')    f=-1;
	for (;ch>='0'&&ch<='9';ch=getchar())	x=(x<<1)+(x<<3)+ch-'0';
	return x*f;
}
inline void print(int x){
	if (x>=10)     print(x/10);
	putchar(x%10+'0');
}
const int N=1e5;
int prime[N+10];
bool inprime[N+10];
int tot,n,p,Ans;
void prepare(){
	for (int i=2;i<=N;i++){
		if (!inprime[i])	prime[++tot]=i;
		for (int j=1;j<=tot&&i*prime[j]<=N;j++){
			inprime[i*prime[j]]=1;
			if (i%prime[j]==0)	break;
		}
	}
}
int phi(int x){
	int ans=x;
	for (int i=1;prime[i]*prime[i]<=x;i++){
		if (x%prime[i])	continue;
		ans-=ans/prime[i];
		while (x%prime[i]==0)	x/=prime[i];
	}
	if (x!=1)	ans-=ans/x;
	return ans;
}
int mlt(int a,int b){
	
	int res=1;
	for (;b;b>>=1,a=1ll*a*a%p)	if (b&1)	res=1ll*res*a%p;
	return res;
}
int main(){
	prepare();
	for (int Data=read();Data;Data--){
		n=read(),p=read(),Ans=0;
		for (int i=1;i*i<=n;i++){
			if (n%i)	continue;
			int j=n/i;
			Ans=(Ans+1ll*mlt(n,i-1)*phi(j))%p;
			if (i!=j)	Ans=(Ans+1ll*mlt(n,j-1)*phi(i))%p;
			//省时间,枚举到sqrt(n)即可,判下是否为完全平方数
		}
		printf("%d\n",Ans);
	}
	return 0;
}
posted @ 2018-03-06 20:07  Wolfycz  阅读(291)  评论(0编辑  收藏  举报