Hello, I would not know how to generate BigInteger of constant n
length . K
I found this algorithm here:
BigInteger r;
Random rnd = new Random(System.currentTimeMillis());
do {
r = new BigInteger(n.bitLength(), rnd);
} while (r.compareTo(n) >= 0);
This successfully generates random numbers in a range, but it's not what I'm looking for, what I'm looking for is for example:
Input
n = 3
k = 5
Output
12345
54321
67854
I suppose that the "constant length K" actually refers to the fact that, written the number in decimal base, the number of digits is K.
(Never confuse a number -a mathematical entity- with its representation; for example:
251
0xFB
2.51E2
CCLI
they are different representations -in decimal, hexadecimal, scientific and Roman notation- but the number is one and the same in all four cases; they are not four numbers, it is only one written in different ways)In this case, if for example K=5 you have to generate in the range 10000 to 99999, that is, between 10^(K-1) and 10^K-1
The most efficient way to generate random BigIntegers is by directly generating the bits , but that doesn't directly fit a decimal range. (although it can be done, generating uniform values in the range 0 - 2^j-1 for some j such that 2^j >= 10^(k+1) and checking if it falls within our range, if not we retry)
Another easy option is to directly generate the number as a string and then convert it to BigInteger
Or, something more elegant (I don't know if more efficient) using BigInteger arithmetic:
Both can be optimized a bit, if you are going to use them repeatedly: the Random object should be instantiated only once, for example. And in the second implementation, we could pre-set the ten BigInteger 0-9 into an array.
You can build a string representation of the random values using the `BigInteger(String val)' constructor: