【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
Sample Output
View Code
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
相关文章推荐
- [数论] HOJ 1356 Prime Judge Miller Rabin+快速幂
- hoj1356 Miller_Rabbin算法
- [SinGuLaRiTy-1002] Miller Rabin Prime Judge 米勒·罗宾素数判定法
- 素数检测-Miller_Rabin算法-hoj1356-nod1186质数检测V2
- hoj 1004 Prime Palindromes 回文素数
- LightOJ 1356 Prime Independence( Hopcroft–Karp Bipartite算法)
- POJ 1811 Prime Test(素数判定Miller-Rabin+素因子分解Pollard-rho)
- C++实现的Miller-Rabin素性测试程序
- Lightoj-1356 Prime Independence(质因子分解)(Hopcroft-Karp优化的最大匹配)
- python judge prime number
- LightOj1356-Prime Independence
- POJ 1811 Prime Test (miller_rabin + pollard_rho)
- Hoj 1004 Prime Palindromes
- Hoj 2276 Count prime
- LightOJ 1356 Prime Independence 二分图最大独立集,HK算法
- hdu2138 How many prime numbers(Miller_Rabbin随机素数测试)
- Hoj 1356 Prime Judge
- Miller_Rabin素性测试学习小结
- hoj 1015 Nearly prime numbers
- USACO-Section 1.5 Prime Palindromes(Miller-Rabin)