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
//
#include<iostream> #include<cstring> #include<cstdio> using namespace std; #define maxn 36000 int n, mod, ans; int prim[35000]; bool flag[maxn + 20];
void get_prim() { memset(flag, 0, sizeof (flag)); for (int i = 2; i <= 1000; i++)if (!flag[i]) for (int j = i * i; j <= maxn; j += i)flag[j] = true; for (int i = 2, k = 0; i <= maxn; i++) if (!flag[i])prim[k++] = i; }
int eular(int n) { int i = 0, ans = 1; for (i = 0; prim[i] * prim[i] <= n; i++) { if (n % prim[i] != 0)continue; ans *= prim[i] - 1; n /= prim[i]; while (n % prim[i] == 0) { ans *= prim[i]; n /= prim[i]; } } if (n > 1)ans *= n - 1; return ans % mod; }
int f(int c, int k, int mod) { int ans = 1; c = c % mod; while (k) { if (k & 1)ans = (c * ans) % mod; k >>= 1; c = (c * c) % mod; } return ans; }
int main() { get_prim(); int i, T; scanf("%d", &T); while (T-- && scanf("%d%d", &n, &mod)) { ans = 0; for (i = 1; i * i <= n; i++) { if (i * i == n)//枚举循环长度l,找出相应的i的个数:gcd(i,n)=n/l. ans = (ans + f(n, i - 1, mod) * eular(i)) % mod; else if (n % i == 0)//有长度为l的循环,就会有长度为n/l的循环。 ans = (ans + f(n, n / i - 1, mod) * eular(i) + eular(n / i) * f(n, i - 1, mod)) % mod; } printf("%d\n", ans); } }