You can use the BigInteger constructor, where you specify the number of binary digits: BigInteger(int numBits, Random rnd) . You need approximately ten binary digits for every three decimal digits that the user wants. For example, if you need a 30-digit random BigInt , use 100 binary digits.
You can cut off unnecessary digits with remainder(10^30) and do it in a loop to ensure that the starting digit is not zero, providing the correct number of digits, for example:
Random rnd = new Random(123); BigInteger tenPow30 = new BigInteger("10").pow(30); BigInteger min = new BigInteger("10").pow(29); BigInteger r; do { r = new BigInteger(100, rnd).remainder(tenPow30); } while (r.compareTo(min) < 0); System.out.println(r);
Link to the demo.
source share