【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

 

转载于:https://www.cnblogs.com/hoskey/p/4371853.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值