-1

Possible Duplicate:
How to generate a random BigInteger value in Java?

I'm using BigInteger class in JAVA, and I want to generate random numbers from 1 to x-1 . I'm not sure how to do that?

I cannot use nextInt() since it only accepts int not BigIntegers also, I'll be generating 32bit and above numbers so, even nextInt() will not work.

I know If I search I may find some helpful solutions, but I'm so short in time. (2 hours before deadline)

Thanks in Advance.

Community
  • 1
  • 1
Sobiaholic
  • 2,927
  • 9
  • 37
  • 54

2 Answers2

1

May this work

    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;
    }
vels4j
  • 11,208
  • 5
  • 38
  • 63
  • This is computationally very expensive in cases where the last digit of the biginteger is small – ammcom May 21 '17 at 11:34
0

Just use the constructor that get Random

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

If you want between 0 and some number, you can generate the same number of bits as that number and generate random numbers until you get one lesser then it.

(Code not tested)

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;
}
Aviram Segal
  • 10,962
  • 3
  • 39
  • 52
  • 3
    I don't want to put the max number of bits. I want to generate from 1 to n-1 . for example I have a 9349999999 and I want to find a random between 1 to 9349999999 -1 . How to do it in big integer? – Sobiaholic Dec 22 '12 at 19:22