xref: /plan9/sys/src/libc/port/ntruerand.c (revision 9a747e4fd48b9f4522c70c07e8f882a15030f964)
1 #include <u.h>
2 #include <libc.h>
3 
4 ulong
ntruerand(ulong n)5 ntruerand(ulong n)
6 {
7 	ulong m, r;
8 
9 	/*
10 	 * set m to the one less than the maximum multiple of n <= 2^32,
11 	 * so we want a random number <= m.
12 	 */
13 	if(n > (1UL<<31))
14 		m = n-1;
15 	else
16 		/* 2^32 - 2^32%n - 1 = (2^32 - 1) - (2*(2^31%n))%n */
17 		m = 0xFFFFFFFFUL - (2*((1UL<<31)%n))%n;
18 
19 	while((r = truerand()) > m)
20 		;
21 
22 	return r%n;
23 }
24