Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get random BigInteger in range (x, y) [duplicate]

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

like image 313
user3132352 Avatar asked Apr 14 '14 07:04

user3132352


Video Answer


2 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);
like image 104
apangin Avatar answered Oct 22 '22 10:10

apangin


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
like image 40
TheWalkingCube Avatar answered Oct 22 '22 10:10

TheWalkingCube