当 运行 我的代码 [BigInteger] 时没有任何反应

Nothing happens when running my code [BigInteger]

所以我有一个 class 计算两个素数然后检查它们是否是素数

import java.util.*;
import java.math.*;

public class GeneratePrime{

  public static BigInteger calculatePPrime() {
    BigInteger pRandom;
    while (true) {
      pRandom = new BigInteger(512, new Random());
      pRandom = pRandom.setBit(0); 
      if(isPrime(pRandom)){
        System.out.println("Got Random Prime P: "+pRandom);
        break;
      }
    }
    return pRandom;
  }

  public static BigInteger calculateQPrime() {
    BigInteger qRandom;
    while(true){
      qRandom = new BigInteger(512, new Random());
      if(isPrime(qRandom)){
        System.out.println("Got Random Prime Q: "+qRandom);
        break;
      }
    }
    return qRandom;
  }

  public static boolean isPrime(BigInteger number) {
    if (!number.isProbablePrime(5))
        return false;

    BigInteger two = new BigInteger("2");
    if (!two.equals(number) && BigInteger.ZERO.equals(number.mod(two)))
        return false;

    for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(number) < 1; i = i.add(two)) {
        if (BigInteger.ZERO.equals(number.mod(i)))
            return false;
    }
    return true;
  }
}

这或多或少是我在 Internet 上找到的东西的集合体。这个class本来没有使用任何BigIntegers,但后来我发现我需要用它来完成我的作业,所以我不得不从头开始做这个。

总之。我不能使用任何内置函数来计算素数(idk,如果有的话)。我的问题是,当我 运行 此代码位于:

import java.util.*;
import java.math.*;

public class RSA{
    public static void main(String[] args) {
        BigInteger p, q;
        GeneratePrime gp = new GeneratePrime();
        p = gp.calculatePPrime();
        q = gp.calculateQPrime();
    }
}

两个 class 都编译得很好,但是当我 运行 RSA class 时,没有任何反应。没有错误没有什么。我的终端是空白的。有谁知道为什么?或者任何人都可以查看此代码是否可以在他们的机器上运行?我知道我可能在这里错过了一些愚蠢的东西。谢谢

新 BigInteger 的最大 bitLength 值非常大。如果将其减少到较小的数量,它将起作用。我指的是下面代码中的值 512。试试像 12 这样的小数字。

pRandom = new BigInteger(512, new Random());

您想获得随机素数吗?然后在您的代码中明确说明:

public BigInteger randomPrime(int bits, Random random) {
  return new BigInteger(bits, random).nextProbablePrime();
  // or
  // return BigInteger.probablePrime(bits, random);
}

使用您可以使用的方法,在本例中为:nextProbablePrime()。这个方法比你写的那组方法要高效得多。这将显着提高您的应用程序。

您的 RSA class 可以变成:

import java.util.*;
import java.math.*;

public class RSA{
    public static void main(String[] args) {
        BigInteger p, q;
        GeneratePrime gp = new GeneratePrime();
        Random random = new Random();
        int bits = 512;
        p = gp.randomPrime(bits, random);
        q = gp.randomPrime(bits, random);
    }
}

如果你愿意使用512位的数字,你想随机得到它,希望它是一个素数。你会发现你的解决方案没有成功。这是一个太大的值,无法处理太多的可能性。即使您在 certainty 中使用 BigInteger 构造函数。像这样:

new BigInteger(int bitLength, int certainty, Random random);

java 文档说:

certainty - a measure of the uncertainty that the caller is willing to tolerate. The probability that the new BigInteger represents a prime number will exceed (1 - 1/(2certainty)).

certainty越大,这个数不是质数的概率就越小

还是帮不了你。如果随机数不是 @Olivier Grégoire 建议的素数,或者只是减少位数,您可以考虑只取下一个素数。