Blame


1 0fc65b37 2004-03-21 devnull #include <u.h>
2 0fc65b37 2004-03-21 devnull #include <libc.h>
3 0fc65b37 2004-03-21 devnull #include <libsec.h>
4 0fc65b37 2004-03-21 devnull
5 0fc65b37 2004-03-21 devnull #define Maxrand ((1UL<<31)-1)
6 0fc65b37 2004-03-21 devnull
7 0fc65b37 2004-03-21 devnull ulong
8 0fc65b37 2004-03-21 devnull nfastrand(ulong n)
9 0fc65b37 2004-03-21 devnull {
10 0fc65b37 2004-03-21 devnull ulong m, r;
11 fa325e9b 2020-01-10 cross
12 0fc65b37 2004-03-21 devnull /*
13 0fc65b37 2004-03-21 devnull * set m to the maximum multiple of n <= 2^31-1
14 0fc65b37 2004-03-21 devnull * so we want a random number < m.
15 0fc65b37 2004-03-21 devnull */
16 0fc65b37 2004-03-21 devnull if(n > Maxrand)
17 0fc65b37 2004-03-21 devnull sysfatal("nfastrand: n too large");
18 0fc65b37 2004-03-21 devnull
19 0fc65b37 2004-03-21 devnull m = Maxrand - Maxrand % n;
20 0fc65b37 2004-03-21 devnull while((r = fastrand()) >= m)
21 0fc65b37 2004-03-21 devnull ;
22 0fc65b37 2004-03-21 devnull return r%n;
23 0fc65b37 2004-03-21 devnull }