Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating very large random numbers java

How can we generate very large random number in java? I am talking something like 10000 digits? I know we have to use BigInteger but how can we do this? What is the most efficent way of doing something like this? Please provide a small example. Thank you.

like image 316
Jeel Shah Avatar asked Nov 23 '11 15:11

Jeel Shah


2 Answers

Well, one way is to go to Random.org and download a one of the binary random files. The files are generated from atmospheric noise, so it's very random. I used it for Zobrist keys in my chess engine.

Alternatively you could go

BigInteger b = new BigInteger(256, new Random());

which will give you what you want. In this example, a BigInteger consisting of 256 bits.

like image 168
Jaco Van Niekerk Avatar answered Oct 12 '22 11:10

Jaco Van Niekerk


Combine Random.nextBytes(byte[]) with BigInteger(byte[]).

import java.util.*;
import java.math.*;
class Test{
    public static void main(String[]_){

        int n = 16;

        Random r = new Random();
        byte[] b = new byte[n];
        r.nextBytes(b);
        BigInteger i = new BigInteger(b);

        System.out.println(i);
    }
}
like image 39
Vlad Avatar answered Oct 12 '22 09:10

Vlad