1

This is the code to generate a random number from 1 to 10:

int a = (int)(Math.random() * 10) + 1;

But I have been thinking, what if I want to generate a number that is 100 bits randomly? how can I do this with BigInteger datatype?

Astoach167
  • 91
  • 1
  • 7
  • 4
    Does this answer your question? [Generating random BigDecimal value from given range](https://stackoverflow.com/questions/5023421/generating-random-bigdecimal-value-from-given-range) – Amongalen Aug 12 '20 at 10:33
  • It's pretty much the same as generating a number between 0 and the largest number representable by 100 bits. So Amongalen's link is the answer for you. – akuzminykh Aug 12 '20 at 10:41
  • Also `int` is definitely not the correct data type for handling 100bit number – Sanket Bhat Aug 12 '20 at 10:46
  • What **exactly** do you mean by "100 bits randomly"? Like a number between 2^0 and 2^100? – Nico Haase Aug 12 '20 at 11:40

1 Answers1

4

New answer:

The BigInteger class has a constructor that you can use to generate a random number with the given number of bits. This is how you could use it:

BigInteger random(int bits) {
    Random random = new Random();
    return new BigInteger(bits, random);
}

Old answer with a long-winded way of doing the same:

The java.util.Random class has a nextBytes method to fill an array of bytes with random values. You can use that to generate a BigInteger with an arbitrary number of bytes.

The complication is, what to do when number of bits isn't a multiple of 8? My suggestion is to generate one byte too much and get rid of the extra bits with a shift operation.

BigInteger random(int bits) {
    Random random = new Random();
    // One byte too many if not multiple of 8
    byte[] bytes = new byte[(bits + 7) / 8];
    random.nextBytes(bytes);
    BigInteger randomNumber = new BigInteger(1, bytes);
    // Get rid of extra bits if not multiple of 8
    return randomNumber.shiftRight(bytes.length*8 - bits);
}
Joni
  • 108,737
  • 14
  • 143
  • 193
  • may I know for "new BigInteger(1, bytes)", what does the 1 do? I heard that u can put 0 or -1 instead 1 – Astoach167 Aug 12 '20 at 16:34
  • This is the "sign-magnitude" constructor - with 1 you get a positive number, with -1 you get a negative number. With 0 you get a zero, but only if the magnitude was zero itself See https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigInteger.html#%3Cinit%3E(int,byte%5B%5D) – Joni Aug 12 '20 at 16:43