5

I need to get a random BigInteger that is bigger than 2^511 and lower than 2^512.

Filburt
  • 17,626
  • 12
  • 64
  • 115
user3132352
  • 403
  • 1
  • 9
  • 24

4 Answers4

3
byte[] bytes = new byte[64];    // 512 bits
new Random().nextBytes(bytes);
bytes[0] |= 0x80;               // set the most significant bit
return new BigInteger(1, bytes);
apangin
  • 92,924
  • 10
  • 193
  • 247
2

From the doc :

BigInteger(int numBits, Random rnd)

Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2numBits - 1), inclusive.

So something like that should work :

    BigInteger number = new BigInteger(512, new Random()); //Give you a number between 0 and 2^512 - 1
    number = number.setBit(0); //Set the first bit so number is between 2^511 and 2^512 - 1
Community
  • 1
  • 1
TheWalkingCube
  • 2,036
  • 21
  • 26
2

This solution creates at first a BigInteger with value 2^511 and afterwards adds an value between 0 and 2^511 - 1:

StringBuilder builder = new StringBuilder("1");
for (int bit = 0; bit < 511; bit++) builder.append("0");
BigInteger value = new BigInteger(builder.toString(), 2).add(new BigInteger(511, new Random()));
Harmlezz
  • 7,972
  • 27
  • 35
0

You could try that

public static void main(String[] args) {
    int min = 511;
    double rand = Math.random(); //between 0 and 1
    double exp = min + rand; //between 511 et 512

    Double result = Math.pow(2, exp);

    System.out.println("result = ["+result+"]");

}

It is maybe not optimised, but its works. With the double result, you can obtain a integer.

Error418
  • 309
  • 1
  • 11