Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate a random BigInteger within a certain range?

Consider this method that works well:

public static bool mightBePrime(int N) {
    BigInteger a = rGen.Next (1, N-1);
    return modExp (a, N - 1, N) == 1;
}

Now, in order to fulfill a requirement of the class I'm taking, mightBePrime must accept a BigInteger N, but that means that I need a different way to generate my random BigInteger a.

My first idea was to do something like BigInteger a = (N-1) * rGen.NextDouble (), but a BigInteger can't be multiplied by a double.

How can I generate a random BigInteger between 1 and N-1, where N is a BigInteger?

like image 610
Trevor Dixon Avatar asked Jun 28 '13 05:06

Trevor Dixon


People also ask

How do you generate random Bigint?

BigInteger bigInteger = maxLimit. subtract(minLimit); Declare a Random object and find the length of the maxLimit: Random randNum = new Random(); int len = maxLimit. bitLength(); Now, set a new B integer with the length and the random object created above.

How do you generate random integers in range?

Use randrnage() to generate random integer within a range Use a random. randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random. randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).

How to generate a Big random number in Java?

You can just type: int number = (int)(Math. random() * 100);

How much space does BigInteger take?

BigInteger 1 digit = 70B (ex: new BigInteger("9")) BigInteger 20 digits = 80B (ex: new BigInteger("12345678901234567890")) BigInteger 100 digits = 112B.


2 Answers

Paul suggested in a comment that I generate a number using random bytes, then throw it away if it's too big. Here's what I came up with (Marcel's answer + Paul's advice):

public static BigInteger RandomIntegerBelow(BigInteger N) {
    byte[] bytes = N.ToByteArray ();
    BigInteger R;

    do {
        random.NextBytes (bytes);
        bytes [bytes.Length - 1] &= (byte)0x7F; //force sign bit to positive
        R = new BigInteger (bytes);
    } while (R >= N);

    return R;
}

http://amirshenouda.wordpress.com/2012/06/29/implementing-rsa-c/ helped a little too.

like image 81
Trevor Dixon Avatar answered Oct 03 '22 07:10

Trevor Dixon


Use the Random-Class

public BigInteger getRandom(int length){
    Random random = new Random();
    byte[] data = new byte[length];
    random.NextBytes(data);
    return new BigInteger(data);
}
like image 39
masinger Avatar answered Oct 03 '22 08:10

masinger