0

我有一个循环来生成两个素数,我不希望它们相等,它们都需要完全是“数字”数字。我可以让第一个素数(bigInt1)具有所需的长度,但第二个(bigInt2)从“digits”到“digits + 1”不等,我不知道为什么,我花了很多时间查看这段代码我只是找不到解决方案,有人可以帮忙吗?

...
public static BigInteger[] bigInts = new BigInteger[2];
static int digits;


public static void GeneratePrimeBigInt(String stringDigits){

    digits = Integer.parseInt(stringDigits);
    int bits = (int)Math.ceil(Math.log(Math.pow(10,digits))/(Math.log(2))); // convert digits to bits

    // Generate Huge prime Random Number with 1 - 2^(-1000) probability of being prime
    BigInteger bigInt1 = new BigInteger(bits,1000,new Random(System.currentTimeMillis()));
    BigInteger bigInt2 = new BigInteger(bits,1000,new Random(System.currentTimeMillis()));

    while (bigInt1.toString().length() != digits){
        bigInt1 = new BigInteger(bits,1000,new Random(System.currentTimeMillis()));
        }


    // make sure no two bigIntegers are the same
    while(bigInt1.equals(bigInt2)){
        BigInteger bigInt21 = new BigInteger(bits,1000,new Random(System.currentTimeMillis()));
        bigInt2 = bigInt21;
        if ((bigInt2.toString().length()) != digits){
            while (bigInt2.toString().length() != digits){
                BigInteger bigInt22 = new BigInteger(bits,1000,new Random(System.currentTimeMillis()));
                bigInt2 = bigInt22;
            }
        }
    }

    // store results in array for future reference and display results in RsaWindow 
    RsaWindow.setMyLabels(5, "Here are two prime numbers, p and q, 
            of " + digits + "digits");
    bigInts[0] = bigInt1;
    RsaWindow.setMyLabels(7,"p= " + bigInt1.toString());
    bigInts[1] = bigInt2;
    RsaWindow.setMyLabels(8,"q= " + bigInt2.toString());
}
4

3 回答 3

2

BigInteger 的构造函数使用位长度。每次将新数字从二进制转换为十进制时,这不一定是相同的十进制位数。

[编辑] 我之前说的毫无意义。固定的。

一个可能的解决方案是去掉 if,并将其添加到第一个 while 循环中:

while (bigInt1.equals(bigInt2) || bigInt2.toString().length() != digits)

然而,这似乎是一段非常重量级的代码。你到底想完成什么?

于 2013-08-15T18:34:25.737 回答
1

我的测试中的以下代码给出了正确长度的结果:

private static SecureRandom random = new SecureRandom();

public static void generatePrimeBigInt(String stringDigits) {
    int digits = Integer.parseInt(stringDigits);
    int bits = (int) Math.floor(Math.log(Math.pow(10, digits)) / (Math.log(2)));
    BigInteger bigInt1 = BigInteger.ZERO;
    BigInteger bigInt2 = BigInteger.ZERO;
    while (bigInt1.equals(bigInt2)){
        bigInt1 = new BigInteger(bits, 1000, random);
        bigInt2 = new BigInteger(bits, 1000, random);
    }
    //numbers are ready to store or other use at this point
}
于 2013-08-15T18:48:32.213 回答
0

问题在于这一行:

while(bigInt1.equals(bigInt2))

“在 while 语句之后检查 bigInt2 的有效性”。很少有测试用例被遗漏。上述条件也适用于两个不同位数的素数。建议在检查“bigInt1.equals(bigInt2)”之前检查 bigInt2 数字,它将始终有效。

于 2013-08-15T18:56:52.900 回答