Newsgroups: sci.crypt

Subject: Re: modran(x)
Date: Thu, 24 Feb 94 18:59:15 CST
Organization: University of Missouri, Columbia
Lines: 32
Message-ID: <>
References: <>

In article <> (Keith Willis) writes:
>        More generally, given the standard system function rand()
>        which returns numbers in the range 0 to RAND_MAX, what is the
>        correct method for arriving at numbers in the range 0 to N?
>        I'm in no sense a math major, and I have always used the above
>        mod-range method or something similar as being in some way
>        'intuitively obvious'.
   Hmmmm.  Suppose you had a random number generator that always put out
a uniformly distributed number between 0 and 10.  Now, imagine trying to
get evenly distributed decimal digits by taking the output of that function
modulo 10.  You'd get twice as many 0s as any other number, right?
   If you wanted to use this 0..10 generator to get evenly distributed
decimal digits, you'd have to discard 10s when they came up.
   Similarly, suppose you used a generator that put out uniformly distributed
numbers between 0 and 255, and you wanted numbers from 0 to 99.  You could
get this by discarding any generator outputs greater than 199, and taking
the acceptable outputs modulo 100.  In general, if you have random numbers
ranging from 0 to a-1, and you need numbers from 0..b-1, assuming a > b, you
need to throw out all the random numbers greater than or equal to
(a div b) * b.
>Keith Willis      ||         || NO I'M NOT
   --John Kelsey,
   Disclaimer:  I didn't write the FAQ, so I can't tell you if there's any-
                thing else the writer had in mind....