UVA 10006 - 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.
17291756111094310
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^n mod n == a)
思路:先用筛选法打出素数表。然后在用快速幂取模的方法判断条件是否成立
代码:
#include <stdio.h>#include <string.h>#include <math.h>long long n;int vis[65005];void prime() { int s = sqrt(65000 + 0.5); for (int i = 2; i <= s; i ++) {if (!vis[i]) {for (int j = i * i; j <= 65000; j += i)vis[j] = 1;} }}long long pow_mod(long long a, long long n, long long num) { if (n == 1)return a; long long x = pow_mod(a, n / 2, num); long long ans = x * x % num; if (n % 2 == 1)ans = (ans * a) % num; return ans;}int judge() { for (long long i = 2; i < n; i ++) {if (pow_mod(i, n, n) != i) return 0; } return 1;}int main() { prime(); while (~scanf("%lld", &n) && n) {if (vis[n] && judge()) { printf("The number %lld is a Carmichael number.\n", n);}else printf("%lld is normal.\n", n); } return 0;}