poj 2154 color

Color

Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 10383 Accepted: 3378

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


【分析】
低头!http://blog.csdn.net/acdreamers/article/details/8656247
快速幂写错了!快速幂写错了!快速幂写错了!
白学了!退役了!


【代码】

//poj 2154 color 
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(int i=j;i<=k;i++)
using namespace std;
const int mxn=36005;
bool vis[mxn];
int pri[mxn];
int T,n,p,tot;
inline void init()
{
    fo(i,2,36000)
    {
        if(!vis[i]) pri[++tot]=i;
        for(int j=1;j<=tot && i*pri[j]<=36000;j++)
        {
            vis[i*pri[j]]=1;
            if(i%pri[j]==0) break;
        }
    }
}
inline int phi(int x)
{
    int cnt=x;
    for(int i=1;pri[i]*pri[i]<=x;i++)
    {
        if(x%pri[i]==0)
        {
            cnt-=cnt/pri[i];
            while(x%pri[i]==0) x/=pri[i];
        }
    }
    if(x>1) cnt-=cnt/x;
    return cnt%p;
}
inline int ksm(int x,int k)
{
    x=x%p;
    if(k==0) return 1;
    if(k==1) return x;
    int tmp=ksm(x,k>>1);
    if(k&1) return tmp*tmp%p*x%p;
    return tmp*tmp%p;
}
int main()
{
    init();
    scanf("%d",&T);
    while(T--)
    {
        int ans=0;
        scanf("%d%d",&n,&p);
        for(int i=1;i*i<=n;i++)
          if(n%i==0)
          {
              ans=(ans+phi(n/i)*ksm(n,i-1))%p;
              if(i*i==n) continue;
              ans=(ans+phi(i)*ksm(n,n/i-1))%p;
          }
        printf("%d\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值