素数判定 2(codevs 1702)

题目描述 Description

一个数,他是素数么?

设他为P满足(P<=263-1)

输入描述 Input Description

P

输出描述 Output Description

Yes|No

样例输入 Sample Input

2

样例输出 Sample Output

Yes

数据范围及提示 Data Size & Hint

算法导论——数论那一节
注意Carmichael Number

#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;  
}
View Code
原文地址:https://www.cnblogs.com/harden/p/5657572.html