您的位置:首页 > 其它

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

2015-03-27 15:00 232 查看
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 = 100000 + 5;
using namespace std;
typedef long long ll;
ll n;

ll pow(ll a, ll b, ll p){
if (b == 1) return a % p;
ll tmp = pow(a, b / 2, p);
if (b % 2 == 0) 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 != 1 && tmp != (n - 1)) return 0;//不通过
if (tmp == (n - 1) || (p % 2 != 0)) return 1;
return Sec_Check(a, p / 2);
}
bool miller_rabin(ll n){
ll cnt = 20;
while (cnt--){
ll a = (rand()%(n - 1)) + 1;
if (!Sec_Check(a, n - 1)) return 0;
}
return 1;
}

int main(){
srand(time(0));

while (scanf("%lld", &n) != EOF){
if (n == 1) printf("NO\n");
else if (miller_rabin(n)) printf("YES\n");
else printf("NO\n");
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: