random

How to generate a random integer in the range [0,n] from a stream of random bits without wasting bits?


I have a stream of (uniform) random bits from which I'd like to generate random integers uniformly in the range [0,n] without wasting bits. (I'm considering bits wasted which are in excess of floor(log_2(n))+1, on the assumption that it's always possible to use no more than that.) E.g., if n = 5, then the algorithm I'm looking for should use no more than three bits. How can this be done?


Solution

  • This is equivalent to find a two-way function between two set of different (finite) cardinality. It is impossible.