1 /*
2 Copyright (c) 1990 Regents of the University of California.
3 All rights reserved.
4  */
5 #include <stdlib.h>
6 
7 /* Pseudo-random generator based on Minimal Standard by
8    Lewis, Goodman, and Miller in 1969.
9 
10    I[j+1] = a*I[j] (mod m)
11 
12    where a = 16807
13          m = 2147483647
14 
15    Using Schrage's algorithm, a*I[j] (mod m) can be rewritten as:
16 
17      a*(I[j] mod q) - r*{I[j]/q}      if >= 0
18      a*(I[j] mod q) - r*{I[j]/q} + m  otherwise
19 
20    where: {} denotes integer division
21           q = {m/a} = 127773
22           r = m (mod a) = 2836
23 
24    note that the seed value of 0 cannot be used in the calculation as
25    it results in 0 itself
26 */
27 
28 int
rand_r(unsigned int * seed)29 rand_r (unsigned int *seed)
30 {
31         long k;
32         long s = (long)(*seed);
33         if (s == 0)
34           s = 0x12345987;
35         k = s / 127773;
36         s = 16807 * (s - k * 127773) - 2836 * k;
37         if (s < 0)
38           s += 2147483647;
39         (*seed) = (unsigned int)s;
40         return (int)(s & RAND_MAX);
41 }
42