我正在使用BigInteger类生成随机的大素数但我不断得到负值。怎么可能忽略所有负面回报?我应该怎么做到修复10号?
public class Gen{
public static void main(String[] args) throws IOException {
Random rand = new SecureRandom();
BigInteger.probablePrime(100, rand);
System.out.println(BigInteger.probablePrime(100, rand).longValue());
}
}
答案 0 :(得分:4)
您的错误是因为溢出。 Java中的long
只能保存最多9,223,372,036,854,775,807
的值。
如果您的程序生成的大于此值的随机数,则在尝试将其填入long
时可以获得负值。您可以在Javadoc for BigInteger#longValue():
请注意,此转换可能会丢失有关BigInteger值整体幅度的信息,也会返回符号相反的结果。