Plan 9 from User Space's /usr/local/plan9/9pm/src/libc/port/nfastrand.c

#include <9pm/u.h>
#include <9pm/libc.h>

#define Maxrand	((1UL<<31)-1)

ulong
nfastrand(ulong n)
{
	ulong m, r;
	
	/*
	 * set m to the maximum multiple of n <= 2^31-1
	 * so we want a random number < m.
	 */
	if(n > Maxrand)
		abort();

	m = Maxrand - Maxrand % n;
	while((r = fastrand()) >= m)
		;
	return r%n;
}

Space Glenda

Copyright © 2005 Lucent Technologies, Russ Cox, MIT.
See license for details.