【HOJ1356】【Miller_rabin素性测试】Prime Judge

时间:2024-08-20 23:37:02

Given a positive integer, your job is writing a program to determine whether it is a prime number or not.

Input

There are several tests. Each test consists of a positive integer n(no more than 2^31) on a single line. Input is terminated by end of file.

Output

For each integer in the input, print a "YES" if it is a prime number, otherwise print a "NO" instead.

Sample Input

4
5
6

Sample Output

NO
YES
NO
【分析】
素性测试最基本的应用,主要精髓在于费马小定理和二次探测理论。
 /*
五代李煜
《清平乐·别来春半》
别来春半,触目柔肠断。砌下落梅如雪乱,拂了一身还满。
雁来音信无凭,路遥归梦难成。离恨恰如春草,更行更远还生。
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <iostream>
#include <string>
#include <ctime>
#define LOCAL
const int MAXN = + ;
using namespace std;
typedef long long ll;
ll n; ll pow(ll a, ll b, ll p){
if (b == ) return a % p;
ll tmp = pow(a, b / , p);
if (b % == ) return (tmp * tmp) % p;
else return (((tmp * tmp) % p) * (a % p)) % p;
}
//二次探测
bool Sec_Check(ll a, ll p){
ll tmp = pow(a, p, n);
if (tmp != && tmp != (n - )) return ;//不通过
if (tmp == (n - ) || (p % != )) return ;
return Sec_Check(a, p / );
}
bool miller_rabin(ll n){
ll cnt = ;
while (cnt--){
ll a = (rand()%(n - )) + ;
if (!Sec_Check(a, n - )) return ;
}
return ;
} int main(){
srand(time()); while (scanf("%lld", &n) != EOF){
if (n == ) printf("NO\n");
else if (miller_rabin(n)) printf("YES\n");
else printf("NO\n");
}
return ;
}