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