题目链接 http://acm.hust.edu.cn/vjudge/problem/19411
输入n,若满足如下两个条件,则n是Carmichael number
1、n不是素数
2、对于所有a(2<=a<n),有(a^n)%n = a
快速幂取模,注意运算过程中的乘法溢出int
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#define pi acos(-1)
#define LL long long
#define INF 0x3f3f3f3f
using namespace std;
typedef pair<int, int> P;
const int maxn = 1e5 + 5;
const int N = 65005;
int flag[maxn];
void chart()
{
memset(flag, 0, sizeof(flag));
for (int i = 2; i <= N; i++){
if (flag[i]) continue;
for (int j = 2; j * i <= N; j++)
flag[j*i] = 1;
}
}
int q_pow(int x, int n, int mod)
{
int res = 1;
while (n){
if (n & 1) res = (LL)res * x % mod; // 会爆int。。。。
x = (LL)x * x % mod;
n >>= 1;
}
return res;
}
int main(void)
{
// freopen("C:\\Users\\wave\\Desktop\\NULL.exe\\NULL\\in.txt","r", stdin);
int i, j, n, ok;
chart();
while (~scanf("%d", &n) && n)
{
if (!flag[n]){ // 很无语 将这个判断放在后面的话会T
printf("%d is normal.\n", n);
continue;
}
ok = 1;
for (i = 2; i <= n-1; i++){
if (q_pow(i, n, n) != i){
ok = 0;
break;
}
}
if (ok)
printf("The number %d is a Carmichael number.\n", n);
else
printf("%d is normal.\n", n);
}
return 0;
}
本文介绍了一种用于检测Carmichael数的算法,并通过快速幂取模的方法实现了该算法。文章提供了完整的C++代码实现,包括素数标记、快速幂取模函数等关键部分。
491

被折叠的 条评论
为什么被折叠?



