0

I saw many examples to generate random numbers in a specific range [min-max], but i need java code that generates random numbers of n digits or more, so in this case min= 10000000 and no max.

Note - I am using BigInteger

Naman
  • 27,789
  • 26
  • 218
  • 353
rainman
  • 2,551
  • 6
  • 29
  • 43
  • 2
    "no max" assuming you are using `int` or `long`, there is a max: `Integer.MAX_VALUE` or `Long.MAX_VALUE`. – Andy Turner Jul 05 '16 at 14:52
  • 1
    org.apache.commons.lang3.RandomStringUtils may help you here, you can create String that contains only digits with length you need. – dty Jul 05 '16 at 14:53
  • i am using BigInteger – rainman Jul 05 '16 at 14:53
  • Use `long random = new Random().nextLong() + n*10;` – ELITE Jul 05 '16 at 14:53
  • 2
    Even if you're using `BigInteger`, you must have a practical limitation on the number you want to generate. I mean, you could generate a number with as many digits as your heap will allow... but what are you going to do with that? – Andy Turner Jul 05 '16 at 14:55
  • Would suggest using strings in case the use case is well served as pointer by Andy in comments, there has to be a purpose. – Naman Jul 05 '16 at 14:56
  • @Andy i need it for a cryptography algorithm – rainman Jul 05 '16 at 14:59
  • As Andy has pointed out, however, you're going to have to cap it somehow or you'll reach system limitations. – Dando18 Jul 05 '16 at 15:00
  • I know it’s not what you asked, but I want to mention anyway: for cryptography you will probably want to look into SecureRandom (used the right way it can generate digit strings long enough for your cryptographical strength requirements). – Ole V.V. Jul 05 '16 at 15:04
  • http://stackoverflow.com/a/8244798/1746118 does this help/ – Naman Jul 05 '16 at 15:04

2 Answers2

3

You can use the constructor BigInteger(int numBits, Random rnd) to generate positive random numbers with N bits.

As you want to have a minimum, you can add that as an offset to the generated numbers:

Random random = ThreadLocalRandom.current();
BigInteger base = BigInteger.valueOf(10000000); // min
int randomBits = 50; // set as many bits as you fancy

BigInteger rnd = base.add(new BigInteger(randomBits, random));
Peter Walser
  • 15,208
  • 4
  • 51
  • 78
1

BigInteger accepts a decimal String in one of its constructors. Generate individual digits and append them to a String. When you have enough digits in your String, create your BigInteger from the String. You may want to constrain the first digit to be in [1 .. 9] to avoid leading zeros, depending on your exact requirement.

rossum
  • 15,344
  • 1
  • 24
  • 38