我正在编写一个程序来演示 Java 中的 Miller-Rabin 概率测试。代码基本完成了...
import java.util.Random;
import java.util.Scanner;
/**
* Program to demonstrate Miller-Rabin primality testing
*
* @author Nick Gilbert
*/
public class MillerRabin
{
public static void main(String[] args)
{
//Setting up for algorithm
Scanner in = new Scanner(System.in);
Random rn = new Random();
int n = 0, k = 0, m = 0, a = 0;
double b = 0;
boolean probablyPrime = false;
//Asking user for an odd n
do
{
System.out.print("Enter an odd number to test for primality: ");
n = in.nextInt();
}
while(n % 2 == 0);
//Calculating k and m
m = n - 1;
while(m % 2 == 0)
{
m /= 2;
k++;
}
//Generating random a
//a = rn.nextInt(n-1);
//Outputting numbers that will be used in algorithm
System.out.println("k = " + k);
System.out.println("m = " + m);
System.out.println();
a = 86;
System.out.println("A = " + a);
//Running the algorithm
//b_{0}
b = Math.pow(a, m) % n;
System.out.println("b0 = " + b);
if(Math.abs(b) == Math.abs(1 % n)) //Dealing with +/- case via absolute value
{
probablyPrime = true;
}
else
{
//b_{1-(k-1)}
for(int i = 1; i < k; i++) //Going to k-1
{
b = Math.pow(b, 2) % n;
System.out.println("b" + i + " = " + b);
if(Math.abs(b) == Math.abs(1 % n)) //Dealing with +/- case via absolute value
{
probablyPrime = true;
break;
}
}
}
//Printing result
if(probablyPrime)
{
System.out.println("Probably Prime");
}
else
{
System.out.println("Definitely Composite");
}
}
}
我已经硬编码 86 作为我的值来证明我的问题。通过将 a 提高到 m 并取模数 n 第一次计算 b 的地方,数学是不正确的。而不是给出 86 的 b0 是 86^19 % 153 的正确答案,而是给我 b0 等于 107。我已经在调试器中检查了我的值,它们是正确的。我还检查了 a^m 的值,它给了我 86^19 所以问题出现在模数部分。不幸的是,我不知道是什么让数学失败了。