This is a question from CLRS:
Describe an implementation of the procedure RANDOM(a, b) that only makes calls to RANDOM(0, 1). What is the expected running time of your procedure, as a function of $a$ and $b$?
Here RANDOM(a, b) is a random number in the range $a, \ldots, b$.
Here is the answer:
RANDOM(a, b)
range = b - a
bits = floor(log(2, range)) + 1
result = 0
for i = 0 to bits - 1
r = RANDOM(0, 1)
result = result + r << i
if result > range
return RANDOM(a, b)
else return a + result
Now I have some questions: Why has the book used the term randomized algorithm(expected running time which is for randomized algorithms)? Apparently, we call an algorithm randomized when there's some pseudorandom number generator in some part of it. So why has it called this algorithm itself randomized? As a result of RANDOM(0, 1)
? what's the exact definition of a randomized algorithm? Is it possible that this algorithm doesn't terminate ?
if
is always $2^{range}$. A randomized algorithm is an algorithm that has access to an oracle that can generate numbers according to some distribution. Usually this oracle can simulate a fair con flip, i.e., it return $0$ with probability $1/2$ and $1$ with probability $1/2$. All deterministic algorithms are trivially also randomized algorithms (but not vice-versa). $\endgroup$floor(log(2, range) + 1
. I'll edit it. $\endgroup$