1

I need to do a random with a 16-digit number. And the random function I got doesn't work with big numbers. I got this function:

 int pin = new Random().nextInt(10000); 

But if I put a big number like 1000000000000, it won't work because it's not int, and the nextLong is not working to me like that. Thanks.

Baz
  • 36,440
  • 11
  • 68
  • 94
Johnny Dahdah
  • 995
  • 5
  • 15
  • 21
  • Why can you not use `nextLong()` and do divisions and `mod`s? Also, is this math or Java homework? Because if you are doing math homework, there is subtleties involved in getting a uniformly distributed pseudo-random sequence. – Dilum Ranatunga Mar 24 '12 at 04:23
  • `nextLong` and `mod` is a great way to get _bitten_ by the subtleties involved in a uniformly distributed pseudo-random sequence. – Louis Wasserman Mar 24 '12 at 10:55

4 Answers4

3

You could concatenate two random numbers to create a longer random number.

So:

  1. Get an 8 digit random number using nextInt(100000000).
  2. Bit shift it 8 tens digits, or about 10 bits to the left.
  3. Get a second 8 digit random number.
  4. Bitwise OR the two numbers to get your final Long random number.

Does that make sense?

dcow
  • 7,765
  • 3
  • 45
  • 65
1

You could try using a bigInteger, see this post for creating a random big int How to generate a random BigInteger value in Java?

Community
  • 1
  • 1
George Phillips
  • 185
  • 1
  • 2
  • 10
0

You might want to have a look the documentation for Random.nextInt(int n), which discusses the algorithm used, and adapt it to work with longs.

From the documentation:

public int nextInt(int n) {
  if (n <= 0)
    throw new IllegalArgumentException("n must be positive");

  if ((n & -n) == n)  // i.e., n is a power of 2
    return (int)((n * (long)next(31)) >> 31);

  int bits, val;
  do {
    bits = next(31);
    val = bits % n;
  } while (bits - val + (n-1) < 0);
  return val;
}

Follow the link and read the docs for more info.

maybeWeCouldStealAVan
  • 15,492
  • 2
  • 23
  • 32
-1

If you wish to generate arbitrarily large random numbers with N digits, try

StringBuffer buf=new StringBuffer();
rng=new Random();
for(int a=0;a<N;a++)
    buffer.append((char) ('0'+rng.nextInt(10)));
return buffer.toString();
o_o
  • 516
  • 2
  • 9
  • You should not post answers in Homework questions. He's learning, and instead of telling him the answer, we should help him to get to the answer with his own legs. – SHiRKiT Mar 24 '12 at 15:40