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.
source
share