Generating very large random numbers java

浪子不回头ぞ 提交于 2019-11-28 00:27:55

问题


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.


回答1:


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.




回答2:


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);
    }
}



回答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.



来源:https://stackoverflow.com/questions/8244691/generating-very-large-random-numbers-java

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