0

Suppose I take an input "8" from the user, I should be able to generate a random BigInteger of length 8 digits. Suppose I take an input of "20", I should be able to generate a random BigInteger of length 20 digits. How can I achieve this?

I have the following code that I have referred from an example.

int SIZE = 512;
p = new BigInteger(SIZE, 15, new Random());
q = new BigInteger(SIZE, 15, new Random());

Can anyone tell me what those arguments mean? Or else can you suggest an easier method to achieve this?

Sparrow
  • 195
  • 2
  • 5
  • 15
  • 1
    That's not going to generate a uniform distribution. Read the JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger(int,%20int,%20java.util.Random) – Matt Ball Mar 02 '14 at 08:03
  • [How do I generate a random n digit integer in Java using the BigInteger class?](http://stackoverflow.com/questions/3709521/how-do-i-generate-a-random-n-digit-integer-in-java-using-the-biginteger-class) – Michael Yaworski Mar 02 '14 at 08:14

2 Answers2

0

BigInteger(int bitLength, int certainty, Random rnd)

Constructs a randomly generated positive BigInteger that is probably prime, with the specified bitLength. It is recommended that the probablePrime method be used in preference to this constructor unless there is a compelling need to specify a certainty.

Parameters:

bitLength - bitLength of the returned BigInteger.

certainty - a measure of the uncertainty that the caller is willing to tolerate. The probability that the new BigInteger represents a prime number will exceed (1 - 1/2certainty). The execution time of this constructor is proportional to the value of this parameter.

rnd - source of random bits used to select candidates to be tested for primality.

taken straight from Oracles website, hopefully this is what you were looking for.

mig
  • 142
  • 7
-1

An integer solution

public static int randInt(int min, int max) {

    // Usually this can be a field rather than a method variable
    Random rand = new Random();

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

so if you need 8 digit random number

call this function with range in 8 digits i.e smallest 8 digit # and highest 8 digit number .

e.g

randInt(10000000, 99999999)

Source: the code for random number for a range is taken from here

How do I generate random integers within a specific range in Java?

you can look at nextLong() too. These are uniformly generated random numbers

http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextLong()

Community
  • 1
  • 1
Dexters
  • 2,419
  • 6
  • 37
  • 57