Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigInteger q = new BigInteger(8, 10, new Random()); is not producing expected result in Android

BigInteger q = new BigInteger(8, 10, new Random()); is giving me random numbers as expected every time while running from my Desktop but not in Android.

in Android I am always getting only same output instead of random number. Please help me to get random BigIntegr.

for your info:

int randQ = (int) (Math.random() * 9);      
        for (int r = 0; r < randQ; r++) {

            q = q.nextProbablePrime();
        }

is the quick fix that I did and I am not happy with this fix since it is consuming extra time. your suggestions are highly appreciated

like image 274
Abilash Avatar asked Jan 24 '26 11:01

Abilash


1 Answers

This is a very common problem, independent of language or platform.

You must reuse the instance of Random() to get random numbers each time. The default constructor will seed the pseudo-random number generator with the current time. The current time doesn't change very quickly with respect to your program, so you keep getting the same number until the clock ticks up.

If you don't re-seed, it will give you different numbers each time you ask for another value. You can avoid re-seeding by reusing the instance, and calling:

Random random = new Random(); // reuse this instance...
int value = random.nextInt(); // use these values instead of new Random()

See: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Random.html

like image 110
Merlyn Morgan-Graham Avatar answered Jan 26 '26 03:01

Merlyn Morgan-Graham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!