Miller-Rabin素数测试
来源:互联网 发布:知乎网站概述 编辑:程序博客网 时间:2024/05/19 19:35
1.a * b % n
例如: b = 1011101那么a * b mod n = (a * 1000000 mod n + a * 10000 mod n + a * 1000 mod n + a * 100 mod n + a * 1 mod n) mod n
ll mod_mul(ll a, ll b, ll n) { ll res = 0; while(b) { if(b&1) res = (res + a) % n; a = (a + a) % n; b >>= 1; } return res;}
2.a^b % n
ll mod_exp(ll a, ll b, ll n) { ll res = 1; while(b) { if(b&1) res = mod_mul(res, a, n); a = mod_mul(a, a, n); b >>= 1; } return res;}
3.Miller-Rabin测试(测试一个大数是否为素数)
费马小定理:对于素数p和任意整数a,有ap ≡ a(mod p)(同余)。反过来,满足ap ≡ a(mod p),p也几乎一定是素数。
伪素数:如果n是一个正整数,如果存在和n互素的正整数a满足 an-1 ≡ 1(mod n),我们说n是基于a的伪素数。如果一个数是伪素数,那么它几乎肯定是素数。
Miller-Rabin测试:不断选取不超过n-1的基b(s次),计算是否每次都有bn-1 ≡ 1(mod n),若每次都成立则n是素数,否则为合数。
二次探测定理:如果p是奇素数,则 x2 ≡ 1(mod p)的解为 x = 1 || x = p - 1(mod p);
bool miller_rabin(ll n) { if(n == 2 || n == 3 || n == 5 || n == 7 || n == 11) return true; if(n == 1 || !(n%2) || !(n%3) || !(n%5) || !(n%7) || !(n%11)) return false; ll x, pre, u; int i, j, k = 0; u = n - 1; //要求x^u % n while(!(u&1)) { //如果u为偶数则u右移,用k记录移位数 k++; u >>= 1; } srand((ll)time(0)); for(i = 0; i < S; ++i) //进行S次测试 { x = rand()%(n-2) + 2; //在[2, n)中取随机数 if((x%n) == 0) continue; x = mod_exp(x, u, n); //先计算(x^u) % n, pre = x; for(j = 0; j < k; ++j) //把移位减掉的量补上,并在这地方加上二次探测 { x = mod_mul(x, x, n); if(x == 1 && pre != 1 && pre != n-1) return false; //二次探测定理,这里如果x = 1则pre 必须等于 1,或则 n-1否则可以判断不是素数 pre = x; } if(x != 1) return false; //费马小定理 } return true;}
0 0
- Miller - Rabin素数测试
- Miller-Rabin素数测试
- Miller-Rabin(素数测试)
- Miller-Rabin素数测试
- Miller-Rabin素数测试
- Miller-Rabin素数测试
- Miller-Rabin素数测试
- Miller-Rabin 素数测试
- Miller-Rabin素数测试
- Miller-Rabin素数测试
- Miller-Rabin素数测试
- Miller-Rabin素数测试
- Miller-Rabin素数测试
- 素数测试(Miller-Rabin测试)
- 解析 Miller - Rabin 素数测试思想
- Miller-Rabin测试-大素数问题
- 大数判断素数(Miller-Rabin测试)
- C++实现Miller-Rabin素数测试
- poj解题报告——2419
- Android:操作图片Exif信息
- 用myeclipse创建webservice
- Android存储访问及目录
- 浅谈设计模式
- Miller-Rabin素数测试
- 南邮 OJ 1950 比赛现场气氛营造问题
- iOS 9应用开发教程之编辑界面与编写代码
- j2EE通用jar包的作用
- android TeamTalk资料总结-by 樱木
- 小胖说事35-----Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer posi
- Algorithms—82.Remove Duplicates from Sorted List II
- 网站的URL重写
- gulp VS grunk