Java:使用Rabin-Miller测试生成BigInteger随机素数



我试图生成一个随机的大整数,并使用Rabin-Miller测试来检查它是否素数。我不能使用确定性,也不能生成新的大整数素数。我不断得到不是素数的数字。

这是我的代码

public static BigInteger generateRandomPrime(int numBits, Random rand, boolean print) {
  BigInteger result = new BigInteger(numBits, rand);
    BigInteger result2 = new BigInteger(numBits/2, rand);
  int counter=0;
    int res=0;
    if(result.mod(TWO).equals(ZERO))
        result = result.add(ONE);
    while(print==false)
    {
     while(counter<=30 || res!=0)
     {
           res=RabinMillerTest(result, result2, print);
        counter++;
     }
        if(res!=PROBABLY_PRIME)
     {
            result.add(TWO);
        }
     else
        print=true;
    }
    return result;
}

变量counter初始化为零,在内部循环中递增,但从不重置。

假设初始猜测不是素数,则while(counter<=30 || res!=0)循环第一次运行时,counter将增加到31。在外循环的第二次迭代中,counter已经是31。内循环不进行迭代,res保持其值与上一次外循环迭代的值不同。

counter = 0作为外循环中的第一条语句,而不是初始化counter

最新更新