题目大意:判断一个数是否为Carmichael数, (非素数, 并且满足a^n % n == a, a 的取值为2 ~ n - 1)。
解题思路:Eratosthenes筛选法求出素数,然后对应n如果为非素数,就对每个a进行判断,中间用到快速幂。
#include <cstdio> #include <cmath> const int N = 65005; int prime[N] = {0}, M = sqrt(N); int pow_mod(int a, int n, int m) { if (n == 0) return 1; int x = pow_mod(a, n / 2, m); long long ans = (long long)x * x % m; if (n % 2) ans = ans * a % m; return (int)ans; } bool judge(int n) { if (!prime[n]) return false; for (int i = 2; i < n; i++) if (pow_mod(i, n, n) != i) return false; return true; } int main() { for (int i = 2; i < M; i++) if (!prime[i]) for (int j = i * i; j < N; j += i) prime[j] = 1; int n; while (scanf("%d", &n), n) { if (judge(n)) printf("The number %d is a Carmichael number.\n", n); else printf("%d is normal.\n", n); } return 0; }