B
briteguy
Jdk code for nextInt(int) as follows:
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be
positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
I am not sure why the condition:
while(bits - val + (n-1) < 0)
would be necessary to block uneven numbers?
Anyone could explain more on this? Thanks,
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be
positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
I am not sure why the condition:
while(bits - val + (n-1) < 0)
would be necessary to block uneven numbers?
Anyone could explain more on this? Thanks,