You might think that it would suffice to compute rand() % n, which is the remainder when dividing the random integer by n. In practice, this technique fails for two reasons.

The most important reason is pragmatic: rand() really returns only pseudo-random numbers. Many C++ implementations pseudo-random number generators give remainders that aren't very random when the quotients are small integers. For example, it is not uncommon for successive results of rand() to be alternately even or odd. In that case, if n is 2, successive results of rand() % n will alternate between 0 and 1.

There is another, more stable reason to avoid using rand() % n: If the value of n is large, and RAND_MAX is not evenly divisible by n, some remainders will appear more often than others. For example, suppose that RAND_MAX is 32767 (the smallest permissible value of RAND_MAX for any implementation) and n is 20000. In that case, tehre would be two distinct values of rand() tha wold cause rand() % n to be 10000 (namely 10000 and 30000), but only one value of rand() that would cause rand() % n to be 15000 (namely, 15000). Therefore, the naive implementation of nrand would yield 10000 as a value of nrand(20000) twice as often as it would yield 15000.

To aviod these pitfalls, we'll use a different strategy, by dividing the range of available randomnumbers into buckets of exactly equal size. Then we compute a random number and return the number of the coorresponding bucket. Because the buckets are of equal size, some random numbers may not fall into any bucket at all. In that case, we keep asking for random numbers until we get one that fits.

..............................................

forget it I don't want to type all thiis crap.Ther is wya too much. I'm not a professional typer. Get the book.