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

∥☆過路亽.° 提交于 2019-12-23 12:06:06

问题


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


回答1:


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



回答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()));



回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/23054262/get-random-biginteger-in-range-x-y

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!