When using the java.util.Random class, how can I get the value obtained by calling the nextInt () method N times, but in a much more efficient way (in O (1))?
For example, if I create a Random object with a specific initial value, and I want to get the 100,000th value of nextInt () (that is, the value obtained after calling the nextInt () method 100,000 times) in a quick way, can I do this?
For simplicity's sake, suppose JDK version 1.7.06, as you may need to know the exact values โโof some private fields in the Random class. And speaking of this, I found that the following fields matter when calculating a random value:
private static final long multiplier = 0x5DEECE66DL; private static final long addend = 0xBL; private static final long mask = (1L << 48) - 1;
After a bit of randomness research, I found that random values โโwere obtained using a linear congruent generator. The actual method that executes the algorithm is the next (int) method:
protected int next(int bits) { long oldseed, nextseed; AtomicLong seed = this.seed; do { oldseed = seed.get(); nextseed = (oldseed * multiplier + addend) & mask; } while (!seed.compareAndSet(oldseed, nextseed)); return (int)(nextseed >>> (48 - bits)); }
The corresponding line for the algorithm is the one that receives the following initial value:
nextseed = (oldseed * multiplier + addend) & mask;
So, to be more specific, is there a way I can generalize this formula to get the nth nextseed value? I assume that after that I can simply get the nth int value by setting the "bits" variable to 32 (the nextInt () method just calls the next (32) and returns the result).
Thank you in advance
PS: Perhaps this is a question more suitable for mathexchange ?
user2027342
source share