2012-12-22 62 views
-1

可能重複:
How to generate a random BigInteger value in Java?生成隨機數在Java BigIntegers

我在Java中使用的BigInteger類,我想生成隨機數從1 to x-1。我不知道該怎麼做?

我不能使用nextInt()因爲它只接受intBigIntegers也,我將產生32位以上的數字,所以,即使nextInt()將無法​​正常工作。

我知道如果我搜索,我可能會找到一些有用的解決方案,但我時間太短。 (截止日期前2小時)

在此先感謝。

回答

1

可能這項工作

public static void main(String[] args) { 
     BigInteger bigInteger = new BigInteger("9349988899999"); 
     BigInteger bigInteger1 = bigInteger.subtract(new BigInteger("1")); 
     System.out.println(randomBigInteger(bigInteger1)); 
    } 

    public static BigInteger randomBigInteger(BigInteger n) { 
     Random rnd = new Random(); 
     int maxNumBitLength = n.bitLength(); 
     BigInteger aRandomBigInt; 
     do { 
      aRandomBigInt = new BigInteger(maxNumBitLength, rnd); 
      // compare random number lessthan ginven number 
     } while (aRandomBigInt.compareTo(n) > 0); 
     return aRandomBigInt; 
    } 
+0

如果biginteger的最後一位數字很小,這在計算上非常昂貴 – ammcom

0

只需使用constructor即得到Random

Random rnd = new Random(); 
BigInteger i = new BigInteger(maxNumOfBits, rnd); 

如果你想0和若干間,您可以生成相同的位數,這個數字併產生隨機數,直到你得到一個較小的則。

(代碼未測試)

public static BigInteger randomBigInteger(BigInteger maxNum) { 
    Random rnd = new Random(); 
    int maxNumBitLength = maxNum.bitLength(); 
    BigInteger rndNum; 
    do { 
     rndNum = new BigInteger(maxNumBitLength, nd); 
    } while(result.compareTo(upperLimit) >= 0); 
    return result; 
} 
+2

我不想把位的最大數量。我想從1到n-1生成。例如我有一個9349999999,我想在1到9349999999 -1之間找到一個隨機值。如何做大整數? – Sobiaholic