Codevs 1702 素数判定 2(Fermat定理)

1702 素数判定 2
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 钻石 Diamond
传送门
题目描述 Description
一个数,他是素数么?
设他为P满足(P<=263-1)
输入描述 Input Description
P
输出描述 Output Description
Yes|No
样例输入 Sample Input
2
样例输出 Sample Output
Yes
数据范围及提示 Data Size & Hint
算法导论——数论那一节
注意Carmichael Number
分类标签 Tags
素数判定 数论

#include<iostream>
#include<cstdio>
#define LL long long
using namespace std;
LL n;
int s[]={2,3,5,7,11,13,17,19,23,29};
LL slowmi(LL a,LL b)
{
    LL tot=0;
    for(LL i=a;i;i>>=1)
    {
        if(i&1) tot=(tot+b)%n;
        b=(b+b)%n;
    }
    return tot%n;
}
LL mi(LL a,LL b)
{
    LL tot=1;
    for(LL i=a;i;i>>=1)
    {
        if(i&1) tot=slowmi(tot,b)%n;
        b=slowmi(b,b)%n;
    }
    return tot%n;
}
bool check()
{
    if(n==2) return true;
    else if(n<2||!(n&1))  return false;
    for(int i=0;i<10;i++)//费马小定理10次计算 
    {
        if(n==s[i])return true;
        if(mi(n-1,s[i])!=1) return false;
    }
    return true;
}
int main()
{
    cin>>n;
    if(check()) 
      printf("Yes");
    else printf("No");
    return 0;  
}
posted @ 2016-07-10 13:24  nancheng58  阅读(137)  评论(0编辑  收藏  举报