1

我正在编写一个程序来演示 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 所以问题出现在模数部分。不幸的是,我不知道是什么让数学失败了。

4

3 回答 3

2

doubleJava(和任何 IEEE 系统)中的精度只有 15-16 位的精度。如果您使用大于此的数字,您将收到表示错误。

您最有可能需要做的是使用 BigInteger,它不仅可以处理任意精度,而且还具有针对幂和模数进行优化的方法。

// 86^19 % 153
BigInteger result = BigInteger.valueOf(86).modPow(BigInteger.valueOf(19), BigInteger.valueOf(153));
System.out.println(result);

印刷

86
于 2015-03-30T02:41:03.843 回答
1

在这里,Math.pow 返回一个双精度数,因此取一个双精度数的模数将无济于事(永远不要对双精度数使用 Mod,没有人对您得到的结果负责)。

请注意,(89^19) 大约是 2^122,因此 unsigned long(2^64-1) 不会保存这些数字。double 的精度为 2^53(永远不要使用 double 来 mod,数论是整数)。尝试较小的值或使用BigInteger类。

于 2015-03-30T02:39:45.547 回答
0

原始数据类型具有可能限制其准确性的设置大小。

Java 有BigInteger类,它可能适用于您的场景。

于 2015-03-30T02:40:28.460 回答