plan9port

fork of plan9port with libvec, libstr and libsdb
Log | Files | Refs | README | LICENSE

nfastrand.c (353B)


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