Carmichael Numbers |
However, some probabilistic tests exist that offer high confidence at low cost. One of them is the Fermat test.
Let a be a random number between 2 and n - 1 (being n the number whose primality we are testing). Then, n is probably prime if the following equation holds:
Unfortunately, there are bad news. Some numbers that are not prime still pass the Fermat test with every number smaller than themselves. These numbers are called Carmichael numbers.
In this problem you are asked to write a program to test if a given number is a Carmichael number. Hopefully, the teams that fulfill the task will one day be able to taste a delicious portion of encrypted paella. As a side note, we need to mention that, according to Alvaro, the main advantage of encrypted paella over conventional paella is that nobody but you knows what you are eating.
1729 17 561 1109 431 0
The number 1729 is a Carmichael number. 17 is normal. The number 561 is a Carmichael number. 1109 is normal. 431 is normal.
Carmichael数肯定是个合数,且对于所有a都满足a^n mod n = a。
根据题目,按部就班的做。
在对乘方求模的时候可以使用递归的方法,减少计算时间:
(a mod n) ^ p mod n = ((a mod n) ^ (p / 2) mod n) * ((a mod n) ^ (p / 2) mod n) * ((a mod n) ^ (p % 2) mod n) mod n
注意不要超过整型范围,增加取模次数,使用long long类型。
不超过100000的16个卡迈克数如下:
561,1105,1729,2465,2821,6601,8911,10585,15841,29341,41041,46657,52633,62745,63973,75361。
#include <iostream> #include <algorithm> #include <cmath> using namespace std; int isPri(int n) { for(int i = 2; i <= sqrt(n); i++) { if(n % i == 0) { return 0; } } return 1; } long long powmod(int a, int p, int n) { if(p == 1) { return a % n; } if(p == 0) { return 1 % n; } return (powmod(a, p / 2, n) % n) * (powmod(a, p / 2, n) % n) * (powmod(a, p % 2, n) % n) % n; } int isCar(int n) { if(isPri(n)) { return 0; } for(long long a = 2; a < n; a++) { if(powmod(a, n, n) != a) { //cout << a << endl; return 0; } } return 1; } int main(void) { //cout << powmod(747, 1729, 1729) << endl; while(1) { int n; cin >> n; if(n == 0) { break; } if(isCar(n)) { cout << "The number " << n << " is a Carmichael number." << endl; } else { cout << n << " is normal." << endl; } } return 0; }
(全文完)
Carmichael Numbers - UVa10006,布布扣,bubuko.com
原文:http://blog.csdn.net/milkcu/article/details/23553323