POJ2154——Color(Polya定理+筛素数+欧拉函数)

Color
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 6292 Accepted: 2090
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

解析:

        Poj2154的N比较大,10^9的范围,但是只有旋转这种置换,没有翻转。
        如果我们按照O(n)的做法,即∑m^gcd(n,i),显然是要超时的,所以需要换一种思路来计算。 
        设循环节长度为a=gcd(n,i),则一个循环的长度为L=n/a。由以上两式可以得到gcd(L*a,k*a)=a,其中k为不超过L的整数。进一步化简得到gcd(L,k)=1,那么满足这个式子的         循环的个数,也就是k的个数,就是euler(L),euler代表欧拉函数(小于L且与L互质的数的个数)。
        所以答案就是(∑euler(L)*m^(n/L)) / n,本题中m=n,上式也就是(∑euler(L)*n^(n/L-1)。因此只需要枚举n的约数L,L从1枚举到sqrt(n)即可,因为另一个约数就是n/L。注意         当L*L=n的时候别重复算。时间复杂度O(n^0.5logn)。

代码:

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

int n,mod,test,m=0;
bool col[50000];
int a[32000];

void prime(int n)
{
    for(int i=2;i<=n;i++)
    {
        if(!col[i])
        {
            a[++m]=i;
            for(int j=i*i;j<=n;j+=i)col[j]=true;
        }
    }
}

int quick(int a,int b)
{
    int tmp=1;
    for(a%=mod;b;b>>=1)
    {
        if(b&1)tmp=tmp*a%mod;
        a=a*a%mod;
    }
    return tmp;
}

int euler(int n)
{
    int tmp=n;
    for(int i=1;i<=m,a[i]*a[i]<=n;i++)
        if(n%a[i]==0)
        {
            tmp=tmp/a[i]*(a[i]-1);
            while(n%a[i]==0)n/=a[i];
        }
    if(n>1)tmp=tmp/n*(n-1);
    return tmp%mod;
}
int main()
{
    freopen("poj2154.in","r",stdin);
    freopen("poj2154.out","w",stdout);
    scanf("%d",&test);
    prime(32000);
    while(test--)
    {
        int ans=0,i;
        scanf("%d%d",&n,&mod);
        for(i=1;i*i<n;i++)
            if(n%i==0)ans=(ans+euler(i)*quick(n,n/i-1)+euler(n/i)*quick(n,i-1))%mod;
        if(i*i==n)ans=(ans+euler(i)*quick(n,i-1))%mod;
        printf("%d\n",ans);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值