Why 2^31 is not divisible by n?

前端 未结 3 1309
梦如初夏
梦如初夏 2021-01-18 15:39

http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt%28int%29 says:

The algorithm is slightly tricky. It rejects values that would r

相关标签:
3条回答
  • 2021-01-18 15:51

    2^31 is only divisibale by a power or 2. When you check the code, this special case is treated separately without a loop. The Description is related to the rejecting-process, and there n is not a power of 2.

    0 讨论(0)
  • 2021-01-18 16:02

    Regarding the first question:

    As I understand the sentence, it's said that an uneven distribution is caused when 2^31 is not divisible by n.

    I'm sorry but I don't know for the second question.

    0 讨论(0)
  • 2021-01-18 16:04

    This is a problem caused any time you want to generate a random number in a smaller range from one in a larger range where the size of the smaller range isn't divisible by the size of the larger.

    If you had a random number between 0 and 9 (inclusive) and wanted to change it to one between 0 and 3, if you just did this trivially as n%4, you'd have a 3/10 chance of getting a 0 (0, 4 or 8)%4, but a 2/10 chance of getting a 3 (3 or 7)%4. The simplest way around this here is to just re-generate the random number if it's greater than 7.

    The worst case it's talking about is when the size of the smaller range is just over half the size of the larger one, so you'll have to re-generate just over half of the time.

    0 讨论(0)
提交回复
热议问题