2013-05-05 33 views
0

我正在使用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()); 
    } 
} 
+1

什麼是'rann'?你的意思是'rand'? – 2013-05-05 08:33:26

+0

你不能使用Math.abs嗎? – 2013-05-05 08:34:08

+9

「*返回一個**肯定的** BigInteger,可能是素數*」 - 你如何得到一個負數?你確定你在看正確的輸出嗎? – Maroun 2013-05-05 08:34:29

回答

4

您的錯誤是由於溢出。 Java中的long只能保存最大值爲9,223,372,036,854,775,807的值。

如果您的程序生成的隨機數大於此值,則當您嘗試將其填充到long中時,可以得到負值。您可以在Javadoc for BigInteger#longValue()看到:

注意,此轉換會丟失關於BigInteger的值的總體規模信息以及符號相反返回結果。

+0

gosh ......除了long之外,有沒有反正存儲更大的數字? – newbieprogrammer 2013-05-05 08:59:54

+0

'BigInteger'是最常用的一個,難道你不能將它轉換爲'long'嗎? – Keppil 2013-05-05 09:02:23