Color
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 4071 | Accepted: 1371 |
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.
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
解法就是用波利亚原理
不知道为什么,我用__int64就会超时,但是用int就会WA
我考虑到可能是二分幂的时候会超过int,于是换了很多个写法的二分幂模板。最后只有一个可以过
我的代码:
#include<stdio.h> #include<string.h> typedef int ll; ll prime[35000],m; bool flag[35000]; ll eular(ll n) { ll ret=1,i; for(i=2;i*i<=n;i++) { if(n%i==0) { ret=ret*(i-1); n=n/i; while(n%i==0) { n=n/i; ret=ret*i; } } if(n==1) break; } if(n>1) ret=ret*(n-1); return ret%m; } ll exmod(ll p,ll n) { ll sq=1; while(n>0) { if(n%2==1) sq=sq*p%m; p=(p%m)*(p%m)%m; n/=2; } return sq%m; } int main() { ll n,t,ans,i; scanf("%d",&t); while(t--) { ans=0; scanf("%d%d",&n,&m); for(i=1;i*i<n;i++) { if(n%i==0) { ans=(ans+eular(n/i)*exmod(n,i-1)%m)%m; ans=(ans+eular(i)*exmod(n,n/i-1)%m)%m; } } if(i*i==n) ans=(ans+eular(i)*exmod(n,i-1)%m)%m; printf("%d\n",ans%m); } return 0; }