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. 😛 Does anyone have any suggestions on how to do this?
Share
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.From the docs:
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:
For your particular case (with max = 8180385048), the probability of having to reiterate, even once, is about 4.8 %, so no worries 🙂