-1

重複の可能性:
JavaでランダムなBigInteger値を生成する方法は?

JAVA で BigInteger クラスを使用しており、から乱数を生成したいと考えています1 to x-1。私はそれを行う方法がわからないのですか?

32ビット以上の数値を生成するので、nextInt()動作しintません。BigIntegersnextInt()

検索すれば役立つ解決策が見つかるかもしれませんが、時間がありません。(締め切り2時間​​前)

前もって感謝します。

4

2 に答える 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;
    }
于 2012-12-22T19:47:49.933 に答える