Random number between 0 and n

Given a function R that produces true random 32-bit numbers, I need a function that returns random integers ranging from 0 to n, where n is arbitrary (less than 2 ^ 32).

The function should equally likely produce all values โ€‹โ€‹from 0 to n.

I need a function that runs in constant time without instructions or if loops, so something like the Java function Random.nextInt (n) is missing.

I suspect that a simple module will not do the job if n is not a power of 2 - am I right?


I accepted Jason's answer, despite the fact that he needs a cycle of indefinite duration, since he is apparently the best method to use in practice and, in fact, answers my question. However, I am still interested in any algorithms (even if they are less efficient) that will be deterministic in nature and guaranteed to stop, as Mark Byers pointed out.

+3
source share
5 answers

Without discarding some of the values โ€‹โ€‹from the source, you cannot do this. For example, a set of sizes 2 ^ 32 cannot be divided into three identical sizes. Thus, this cannot be done without discarding some values โ€‹โ€‹and iterations until a nonzero value is output.

So just use this (pseudo code):

rng is random number generator produces uniform integers from [0, max)
compute m = max modulo (n + 1)
do {
    draw a random number r from rng
} while(r >= max - m)
return r modulo (n + 1)

, . rng [0, max), [0, n]

+8

, , . 2 ** 32 .

0 <= x < n, n 2, R . , , , R , .

+3

, , ? R - , 32- , , , , ? , n:

randomNumber = R() % (n + 1) //EDITED: n+1 to return values from 0-n

0 n !

0

32- , 64- . , , 0.99999999976716936, ( , 32 ), , - , .

, " ", 1 .

0

/ , , . getNextRnd() .

, , , ( ) .

0

Source: https://habr.com/ru/post/1726753/


All Articles