10006Carmichael Numbers

来源:互联网 发布:北京北大青鸟网络学校 编辑:程序博客网 时间:2024/06/06 19:30

从这道题里面学习了不少,一个是使用了我之前总结的快速求高次幂的模,第二个就是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 + 10int 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;}


0 0
原创粉丝点击