12

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.

3 Answers 3

22

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.

1
  • 2
    +1. It was four constructors down in the documentation, I didn't see it :D.
    – Vlad
    Commented Nov 23, 2011 at 15:32
9

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);
    }
}
2
  • can you please explain how this works? i'm more or less confused on the bytes part.. thanks
    – Jeel Shah
    Commented Nov 23, 2011 at 15:35
  • You allocate an array of bytes, nextBytes fills it with random values, and then the BigInteger is initialized as the binary number defined by that sequence of bytes. But I think Jaco's solution is more concise.
    – Vlad
    Commented Nov 23, 2011 at 15:37
-3

You can just type:

int number = (int)(Math.random() * 100);

Also, you can generate even bigger numbers if you change the multiplier:

int number = (int)(Math.random() * 1000);

P.S. You don't need to import a class.

3
  • 4
    The question asks for numbers with 10000 digits. This answer does not even come close.
    – TT.
    Commented Feb 7, 2019 at 16:30
  • 1000 digits won't fit into variable of int type. Multiplying random value by some constant makes it not random.
    – gudok
    Commented Feb 7, 2019 at 17:00
  • Although this answer might work for small numbers, the question is clear that it is for very large (much bigger than an int) numbers. So this is not a valid answer.
    – Stefan
    Commented Feb 7, 2019 at 19:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.