从这道题里面学习了不少,一个是使用了我之前总结的快速求高次幂的模,第二个就是Eratosthenes筛选法求解质数,这里给一个链接:http://www.cnblogs.com/color-my-life/p/3265236.html
题目的大意就是:
判断是一个n是不是 满足2个条件:不是素数 + 对于所有的a(2<=a<n), a ^ n % n == a
先打素数表(以后注意,碰到利用素数的题目最好先打表避免超时)
之后快速求模(这里就涉及算法了)
#include<cstdio>
#include<time.h>
#include<cmath>
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
#define MAXD 65000 + 10
int Prime[MAXD];
typedef long long LL;
void Get_Prime(){
memset(Prime,0,sizeof(Prime)); /*一开始都是素数*/
for(int i = 2;i * i < MAXD; i++){
for(int j = i; j * i <MAXD ; j++)
Prime[i * j] = 1; /*不是素数*/
}
}
LL Big_Mod(LL a,LL n,LL mod){
if(n == 0)
return 1 % mod;
LL ans = Big_Mod(a,n/2,mod);
ans = ans * ans % mod;
if(n & 1)
ans = ans * a % mod;
return ans;
}
int main(){
int n;
Get_Prime(); /*打素数表*/
while(scanf("%d",&n) && n){
if(Prime[n]) /*如果不是素数*/{
LL i;
for(i = 2; i < n ; i++)
if(i != Big_Mod(i,n,n))
break;
if(i == n)
printf("The number %d is a Carmichael number.\n",n);
else
printf("%d is normal.\n",n);
}
else
printf("%d is normal.\n",n);
}
return 0;
}
本文介绍了一种用于检测Carmichael数的算法,通过快速求高次幂的模运算和Eratosthenes筛选法预处理素数表来实现。文章提供了完整的C++代码示例,展示了如何判断一个数是否满足特定条件,即该数非素数且对于所有小于它的正整数a,都有a^n%n等于a。
313

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



