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

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
【分析】
素性测试最基本的应用,主要精髓在于费马小定理和二次探测理论。
 1 /*
 2 五代李煜
 3 《清平乐·别来春半》
 4 别来春半,触目柔肠断。砌下落梅如雪乱,拂了一身还满。
 5 雁来音信无凭,路遥归梦难成。离恨恰如春草,更行更远还生。 
 6 */
 7 #include <cstdio>
 8 #include <cstring>
 9 #include <algorithm>
10 #include <cmath>
11 #include <queue>
12 #include <vector>
13 #include <iostream>
14 #include <string>
15 #include <ctime>
16 #define LOCAL
17 const int MAXN = 100000 + 5;
18 using namespace std;
19 typedef long long ll;
20 ll n;
21 
22 ll pow(ll a, ll b, ll p){
23     if (b == 1) return a % p;
24     ll tmp = pow(a, b / 2, p);
25     if (b % 2 == 0) return (tmp * tmp) % p;
26     else return (((tmp * tmp) % p) * (a % p)) % p;
27 }
28 //二次探测
29 bool Sec_Check(ll a, ll p){
30     ll tmp = pow(a, p, n);
31     if (tmp != 1 && tmp != (n - 1)) return 0;//不通过
32     if (tmp == (n - 1) || (p % 2 != 0)) return 1;
33     return Sec_Check(a, p / 2);
34 }
35 bool miller_rabin(ll n){
36     ll cnt = 20;
37     while (cnt--){
38         ll a = (rand()%(n - 1)) + 1;
39         if (!Sec_Check(a, n - 1)) return 0; 
40     }
41     return 1;
42 }
43 
44 int main(){
45     srand(time(0));
46     
47     while (scanf("%lld", &n) != EOF){
48         if (n == 1) printf("NO\n");
49         else if (miller_rabin(n)) printf("YES\n");
50         else printf("NO\n");
51     }
52     return 0;
53 }
View Code

 

posted @ 2015-03-27 15:00  TCtower  阅读(263)  评论(0编辑  收藏  举报