题目描述 Description
一个数,他是素数么?
设他为P满足(P<=2^63-1)
输入描述 Input Description
P
输出描述 Output Description
Yes|No
样例输入 Sample Input
2
样例输出 Sample Output
Yes
数据范围及提示 Data Size & Hint
算法导论——数论那一节
注意Carmichael Number
代码 Code
//来自Solution_ID:14059
#include
#include
typedef long long LL;
using namespace std;
const int primesize = 8;
const int prime[] = {2,3,5,7,11,13,17,19};
LL mul(LL a,LL b,LL m){
return (a*b-(LL)(a/(long double)m*b+1e-3)*m+m)%m;
}
LL ksm(LL a,LL k,LL m){
if(k == 1) return a%m;
if(!k) return 1;
LL b = 1;
while(k){
if(k&1) b = mul(a,b,m);
a = mul(a,a,m);
k /= 2;
}
return b;
}
bool MR(LL x,LL a){
if(x == a) return true;
LL m = x-1;
while(!(m%2)) m /= 2;
LL mi = ksm(a,m,x);
while(m != x-1 && mi != 1 && mi != x-1)
mi = mul(mi,mi,x),m *= 2;
return (m&1 || mi == x-1);
}
bool Isprime(LL x){
if(x == 2) return true;
if(x < 2 || x % 2 == 0) return false;
for(int i = 0;i < primesize;i++){
if(!MR(x,prime[i]))
return false;
}
return true;
}
int main(){
LL x;
scanf("%lld",&x);
if(Isprime(x)) printf("Yes");
else printf("No");
return 0;
}
分析
其实是看完题解打的(凭良心说)
理论基础
MillerRabbin素数判定+二次探测原理