I need to get a random BigInteger that is bigger than 2^511 and lower than 2^512.
Asked
Active
Viewed 5,264 times
5
-
1Here is example code of [Prefactored Random BigInteger](http://stanford.edu/~rezab/useful/PrefactoredRandom.java.html) – Subhrajyoti Majumder Apr 14 '14 at 07:36
4 Answers
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
-
3
-
1There are 2^511-1 integers between 2^511 and 2^512, none of which will fit into a double variable; – VH-NZZ Apr 14 '14 at 07:39
-
-
@okiharaherbst The maximum value of a `Double` is 2^1024. The range is fine, even if the precision is not even slightly enough. – John Dvorak Apr 14 '14 at 07:41
-
@JanDvorak Of course, (although, technically, my comment stating _double_ is not wrong – but i'll gladly concede i was too quick to post :) – VH-NZZ Apr 14 '14 at 07:44