Miller-Rabin素数检测算法

本文介绍了Miller-Rabin素数检测算法,包括费马小定理、二次探测定理等理论基础,并详细阐述了算法过程,如随机选取a、计算x和循环验证等步骤。通过多次循环提高正确率,该算法在判断素数时具有较高效率。

今天看了一下Miller-Rabin素数检测的算法,总结了一下,希望这篇博客对你们有帮助。

 

先说几个理论基础:

1. 费马小定理:假如p是质数,a是整数,且a、p互质,那么a的(p-1)次方除以p的余数恒等于1,即:a^(p-1)≡1(mod p).

但是反过来却不一定成立,就是说,如果a、p互质,且a^(p-1)≡1(mod p),不能推出p是质数,比如Carmichael数。

2. 二次探测定理:如果p是一个素数,0<x<p,则方程x^2≡1(mod p)的解为x=1或x=p-1。

3. 模运算的规则:(a*b)%n=(a%n * b%n)%n

4. 快速积取模、快速幂取模:可以看看我之前写的一篇博客

以下是 Miller-Rabin 素数测试的 Java 代码实现: ```java import java.math.BigInteger; import java.util.Random; public class MillerRabin { private static final int CERTAINTY = 50; // 确定性 public static boolean isPrime(BigInteger n) { if (n.compareTo(BigInteger.ONE) == 0 || n.compareTo(BigInteger.TWO) == 0) { return true; } if (n.mod(BigInteger.TWO).equals(BigInteger.ZERO)) { return false; } BigInteger d = n.subtract(BigInteger.ONE); int r = 0; while (d.mod(BigInteger.TWO).equals(BigInteger.ZERO)) { r++; d = d.divide(BigInteger.TWO); } for (int i = 0; i < CERTAINTY; i++) { BigInteger a = getRandom(n.subtract(BigInteger.TWO)).add(BigInteger.ONE); BigInteger x = a.modPow(d, n); if (x.equals(BigInteger.ONE) || x.equals(n.subtract(BigInteger.ONE))) { continue; } boolean flag = false; for (int j = 0; j < r - 1; j++) { x = x.modPow(BigInteger.TWO, n); if (x.equals(BigInteger.ONE)) { return false; } if (x.equals(n.subtract(BigInteger.ONE))) { flag = true; break; } } if (!flag) { return false; } } return true; } private static BigInteger getRandom(BigInteger n) { Random rnd = new Random(); BigInteger result = new BigInteger(n.bitLength(), rnd); while (result.compareTo(n) >= 0) { result = new BigInteger(n.bitLength(), rnd); } return result; } } ``` 其中,`isPrime` 方法接收一个 `BigInteger` 类型的数值作为输入,返回一个布尔值,表示输入的数值是否为素数。`CERTAINTY` 常量表示测试的确定性,即测试的正确率。一般来说,50 次测试足够保证正确性。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值