随机化一个BigInteger [英] Randomizing a BigInteger

查看:102
本文介绍了随机化一个BigInteger的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找将BigInteger随机化的方法.目的是选择一个从1到8180385048的数字.但是,从我注意到的情况来看,BigInteger(BitLen,Random)将它从n转换为X 2 -1,但我想要一些不可预测的数字.我试图创建一个可以做到这一点的方法,但是我一直遇到错误,最后还是屈服于此. :P有人对此有任何建议吗?

I'm looking to randomize a BigInteger. The intent is to pick a number from 1 to 8180385048. Though, from what I noticed, the BigInteger(BitLen, Random) does it from n to X2-1, I'd want some unpredictable number. I tried to make a method that would do it, but I keep running into bugs and have finally given in to asking on here. :P Does anyone have any suggestions on how to do this?

推荐答案

Judging from the docs of Random.nextInt(int n) which obviously needs to solve the same problem, they seem to have concluded that you can't do better than "resampling if out of range", but that the penalty is expected to be negligible.

从文档中

该算法有些棘手.它拒绝会导致分布不均的值(由于2 31 不能被n整除的事实).值被拒绝的概率取决于n.最坏的情况是n = 2 30 +1,拒绝的概率为1/2,循环终止之前的预期迭代次数为2.

The algorithm is slightly tricky. It rejects values that would result in an uneven distribution (due to the fact that 231 is not divisible by n). The probability of a value being rejected depends on n. The worst case is n=230+1, for which the probability of a reject is 1/2, and the expected number of iterations before the loop terminates is 2.

我建议您只使用

I'd suggest you simply use the randomizing constructor you mentioned and iterate until you reach a value that is in range, for instance like this:

public static BigInteger rndBigInt(BigInteger max) {
    Random rnd = new Random();
    do {
        BigInteger i = new BigInteger(max.bitLength(), rnd);
        if (i.compareTo(max) <= 0)
            return i;
    } while (true);
}

public static void main(String... args) {
    System.out.println(rndBigInt(new BigInteger("8180385048")));
}

对于您的特定情况(最大值为8180385048),即使要重复一次的概率约为4.8%,因此不必担心:-)

For your particular case (with max = 8180385048), the probability of having to reiterate, even once, is about 4.8 %, so no worries :-)

这篇关于随机化一个BigInteger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆