POJ - 2154 Color(波利亚计数)(欧拉函数)

来源:互联网 发布:网络直播很无聊 编辑:程序博客网 时间:2024/06/08 00:21

题目:

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

51 300002 300003 300004 300005 30000

Sample Output

131170629

关于波利亚计数的原理及计算,点击打开链接


在计算这个式子mod p的时候,因为有除n这个运算,这是无法用同余解决的,

除非确定n和p互质,可以找逆元

本题采用的是另外一种方法,直接取定m就是n

那么上式化为


代码:

#include <iostream>using namespace std;int phi(int n){int r = n;for (int i = 2; i*i <= n; i++){if (n%i == 0){while (n%i == 0)n /= i;r = r / i*(i - 1);}}if (n > 1)r = r / n*(n - 1);return r;}int mi(int a, int m, int p){if (m == 0)return 1;int b = mi(a, m / 2, p);b = b*b%p;if (m % 2)b *= a;return b%p;}int main(){int t, n, p, ans;cin >> t;while (t--){cin >> n >> p;ans = 0;int i = 0;while (++i*i < n){if (n%i)continue;ans += phi(n / i) % p*mi(n%p, i - 1, p) % p + phi(i) % p*mi(n%p, n / i - 1, p) % p;}if (i*i == n)ans += phi(i) % p*mi(n%p, i - 1, p) % p;cout << ans%p << endl;}return 0;}

如果对称也算一种的话,就变成了另外一个题目:POJ - 1286 Necklace of Beads(波利亚计数)(欧拉函数)


1 0
原创粉丝点击