题目链接:http://hihocoder.com/problemset/problem/1287?sid=861159
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;
}