生成两个不相等的特定大小的素数

时间:2013-08-15 18:19:38

标签: java loops

我有一个循环来生成两个素数,我不希望它们相等,它们都需要完全正好是“数字”数字。我可以得到第一个素数(bigInt1)所需的长度,但第二个(bigInt2)从“数字”到“数字+ 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());
}

3 个答案:

答案 0 :(得分:2)

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

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

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

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

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

答案 1 :(得分: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
}

答案 2 :(得分:0)

问题在于这一行:

while(bigInt1.equals(bigInt2))

"检查bigInt2的有效性是在while语句"之后完成的。因此错过了很少的测试用例。 对于两个数字不同的素数,上述条件也是如此。建议在检查" bigInt1.equals(bigInt2)"之前检查bigInt2数字。它会一直有效。