Miller-Rabin质数测试
2016-08-27 15:26
330 查看
题目链接:http://hihocoder.com/problemset/problem/1287?sid=861159
费马小定理:对于质数p和任意整数a,
2.Miller-Rabin质数测试
如果满足费马小定理,则进一步验证
一个例子:举个Matrix67 Blog上的例子,假设n=341,我们选取的a=2。则第一次测试时,2^340 mod
341=1。由于340是偶数,因此我们检查2^170,得到2^170 mod
341=1,满足二次探测定理。同时由于170还是偶数,因此我们进一步检查2^85 mod
341=32。此时不满足二次探测定理,因此可以判定341不为质数。
将这两条定理合起来,也就是最常见的Miller-Rabin测试。
2.对于
AC代码
Miller-Rabin质数测试
1.费马小定理:费马小定理:对于质数p和任意整数a,
a^(p-1) mod=1不满足的一定是合数,满足的大概率是素数。
2.Miller-Rabin质数测试
如果满足费马小定理,则进一步验证
如果p是奇素数,则 x^2 ≡ 1(mod p)的解为 x ≡ 1 或 x ≡ p - 1(mod p)
一个例子:举个Matrix67 Blog上的例子,假设n=341,我们选取的a=2。则第一次测试时,2^340 mod
341=1。由于340是偶数,因此我们检查2^170,得到2^170 mod
341=1,满足二次探测定理。同时由于170还是偶数,因此我们进一步检查2^85 mod
341=32。此时不满足二次探测定理,因此可以判定341不为质数。
将这两条定理合起来,也就是最常见的Miller-Rabin测试。
搞清算法后,此题的难点在于对大数运算的处理。
1.对于(a*b)%c这里的a,b,c都是非常大的数因此会产生爆乘,因此不能将a*b直接运算。
2.对于
(a^b%c)这里可以使用快速幂的思想,将指数变成二进制,然后二分的思想。
AC代码
#include<iostream> #include<vector> #include<algorithm> using namespace std; typedef long long ll; ll multmod(ll a, ll b, ll c){//*求(a*b)%c a %= c;b %= c; ll res = 0;ll tmp = a; while (b) { if (b & 1) { res += tmp; if (res > c) res -= c; } tmp <<= 1; if (tmp>c) tmp -= c; b >>= 1; } return res; } ll modpow(ll base, ll exponent, ll modulus) { ll result = 1; while (exponent > 0) { if (exponent & 1) result = multmod(result, base, modulus); exponent >>= 1; base = multmod(base ,base,modulus); } return result; } bool Miller_Rabin(ll n) {//其中n为要测试的数字 if (n <= 2) { if (n == 2)return true; else return false; } if (n % 2 == 0)return false; ll u = n - 1; while (!(u & 1))u = u >> 1; int S = 1000;//S为测试次数 ll x, y; for (int i = 1; i <= S; i++) { int a = (rand() % (n - 1)) + 1;//随机获取一个2 ~ (n - 1)的数字 x = modpow(a, u, n);//x = a ^ u % n,此处用快速幂 while (u < n) { y = modpow(x, 2, n);//此处用快速幂 if (y == 1 && x != 1 && x != n - 1)return false; x = y; u = u * 2; } if (x != 1)return false; } return true; } int main() { int num; cin >> num; ll i; while (num--) { cin >> i; if (Miller_Rabin(i)) cout << "Yes" << endl; else cout << "No" << endl; } return 0; }
相关文章推荐
- 1.m分解阶乘之和
- 2.几种递推数
- 3.欧拉函数
- 4.快速幂模m算法
- 5.扩展欧几里得&&中国剩余定理
- 6.数论_web
- Project Euler Problem 387 - Harshad Numbers - 深度优先
- 编程之美2015初赛A
- HDU 3388 与m,n 互质的第k个整数
- 数论题集
- 原根
- 阶与原根学习笔记
- HDU 1299 Diophantus of Alexandria
- Leftmost Digit(HDU 1060)
- Rightmost Digit(HDU 1061)
- Python-在奇数中寻找素数
- ZOJ 2674 Strange Limit 欧拉定理
- LeetCode-Palindrome Number
- Lucas定理与扩展Lucas
- 除法取模与逆元