gpt4 book ai didi

java - 生成两个不同大小的素数

转载 作者:行者123 更新时间:2023-12-01 23:38:54 26 4
gpt4 key购买 nike

我有一个循环来生成两个素数,我不希望它们相等,并且它们都需要完全是“数字”数字。我可以让第一个素数(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());
}

最佳答案

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

[编辑]我之前说的话毫无意义。已修复。

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

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

然而,这似乎是一段非常重量级的代码。您究竟想要实现什么目标?

关于java - 生成两个不同大小的素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18259095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com