Use the rejection method...

int rand7()
{
    int i;
    do
        i = 5 * rand5() + rand5() - 3;
    while( i > 23 );
    return i / 3;
}

The loop assigns i a value between 5*1+1-3 = 3 and 5*5+5-3 = 27 with
uniform probability, and then rejects any value of i > 23. Thus, after
the loop, i has a uniform distribution on the interval 3 to 23.
Dividing by 3 gives the desired result.

Under the assumptions of the problem, a value of i is rejected with
probability 4/25, so the loop executes an average of 1/(1 - 4/25) =
25/21 times. Therefore, on average, it takes 50/21 rand5's to make a
rand7.

Dave

On Jul 30, 8:33 am, jalaj jaiswal <jalaj.jaiswa...@gmail.com> wrote:
> given a rand5 function which generates numbers from 1 to 5 with equal
> probability.. give an algorithm which uses rand5 function and generates
> numbers from 1 to 7 with equal probability
> --
> With Regards,
> Jalaj Jaiswal
> +919026283397
> B.TECH IT
> IIIT ALLAHABAD

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algoge...@googlegroups.com.
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to