# array of random BigInteger

Hi,
I want to creat an array of  size 10 of  random bigintegers between 1  to  N where N is a biginteger.
thanks,
Anu

###### Who is Participating?

Commented:
java.util.Random rand = new java.util.Random();
BigInteger[] ii = new BigInteger[10];
for (int i = 0; i < 10;i++) {
ii[i] = new BigInteger(32, rand) ;
}
0

Commented:
long[] myArray = new long[10];
Random r = new Random();
for( int i=0; i<10; i++ ) long[i]=r.nextLong();
0

Commented:
With real random bigintegers, that are arbitrary length (!), you would nearly always exhaust your memory :)
0

Commented:
ups, you have a given N, sorry :) I would create a string representation of the integer, by adding up to n numbers. And then assigning them.
0

Commented:
Respect, CEHJ, you are good :)
0

Associate Director - Product EngineeringCommented:
>> random bigintegers between 1  to  N where N is a biginteger
>> ii[i] = new BigInteger(32, rand) ;

I guess the '32' should ideally be replaced with some variable obtained from 'N':

>> between 1  to  N where N is a biginteger

2 ^ numBits - 1 = N
=> 2 ^ numBits = N + 1
=> numBits = log ( N + 1 ) / log 2

That perhaps makes it:

ii[i] = new BigInteger ( Math.log ( N.doubleValue () ) / Math.log ( 2 ), rand ) ;

- Mayank.
0

Commented:
Thanks Mig-O

Mayank's suggestion is good, but that would be

ii[i] = new BigInteger ((int)(Math.log (N.doubleValue()) / Math.log(2)), rand);
0

Associate Director - Product EngineeringCommented:
Argh, forgot to do the (int) conversion :)
0

Commented:
BigInteger already does this calculation for you so all you need to do is:

ii[i] = new BigInteger (N.bitLength(), rand);

NOTE: the N would have to be a multple of 2^N-1 (1,3,7,15,31,63,127,255,511,...)our it would be rounded UP to the nearest multiple.  For example if N was 8 you would get random numbers from 0-15, if N were 256 you would get random numbers from 0-512.
0

Commented:
This leads us to this Equation:

ii[i] = new BigInteger(N.bitLength()*10, rand).divideAndRemainder(N)[1];

This gives values exactly from 0 to N-1, but the values in some upper part of the number range apprear less with a propability of 1/2^10=~0,1%, what seems acceptable.
0

Commented:
ii[i] = new BigInteger(N.bitLength()*10, rand).mod(N);

this is shorter and does the same :)
0

Associate Director - Product EngineeringCommented:
This has been an interesting discussion ;-) revived a lot of Maths I did in college :)
0

Commented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.