Get random BigInteger in range (x, y)

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

+4
source share
4 answers
byte[] bytes = new byte[64];    // 512 bits
new Random().nextBytes(bytes);
bytes[0] |= 0x80;               // set the most significant bit
return new BigInteger(1, bytes);
+3
source

This solution first creates a BigInteger with a value of 2 ^ 511, and then adds a value from 0 to 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()));
+2
source

:

BigInteger (int numBits, Random rnd)

BigInteger, 0 (2numBits - 1) .

, - :

    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
+1

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 may not be optimized, but its work. With a double result, you can get an integer.

0
source

Source: https://habr.com/ru/post/1536399/


All Articles