Initial import from FreeBSD RELENG_4:
[dragonfly.git] / contrib / ntp / libntp / ranny.c
1 /*
2  * Random number generator is:
3  *
4  *      Copyright 1988 by Rayan S. Zachariassen, all rights reserved.
5  *      This will be free software, but only when it is finished.
6  *
7  * Used in ntp by permission of the author.  If copyright is
8  * annoying to you, read no further.  Instead, look up the reference,
9  * write me an equivalent to this and send it back to me.
10  */
11
12 /*
13  * Random number generator; see Knuth Vol 2. 2nd ed. p.27 (section 3.2.2)
14  */
15 #include "ntp_stdlib.h"
16
17 extern  time_t  time            P((time_t *loc));
18
19 /*
20  * 55 random numbers, not all even.  Note we don't initialize ran_y
21  * directly since I have had thoughts of putting this in an EPROM
22  */
23 static time_t ran_y[55];
24
25 static time_t init_ran_y[55] = {
26         1860909544, 231033423, 437666411, 1349655137, 2014584962,
27         504613712, 656256107, 1246027206, 573713775, 643466871,
28         540235388, 1630565153, 443649364, 729302839, 1933991552,
29         944681982, 949111118, 406212522, 1065063137, 1712954727,
30         73280612, 787623973, 1874130997, 801658492, 73395958,
31         739165367, 596047144, 490055249, 1131094323, 662727104,
32         483614097, 844520219, 893760527, 921280508, 46691708,
33         760861842, 1425894220, 702947816, 2006889048, 1999607995,
34         1346414687, 399640789, 1482689501, 1790064052, 1128943628,
35         1269197405, 587262386, 2078054746, 1675409928, 1652325524,
36         1643525825, 1748690540, 292465849, 1370173174, 402865384
37 };
38
39 static int ran_j;
40 static int ran_k;
41
42
43 /*
44  * ranp2 - return a random integer in the range 0 .. (1 << m) - 1
45  */
46 u_long
47 ranp2(
48         int m
49         )
50 {
51         time_t r;
52
53         ran_y[ran_k] += ran_y[ran_j];   /* overflow does a mod */
54         r = ran_y[ran_k];
55         if (ran_k-- == 0)
56             ran_k = 54;
57         if (ran_j-- == 0)
58             ran_j = 54;
59         return (u_long)(r & ((1 << m ) - 1));
60 }
61
62 /*
63  * init_random - do initialization of random number routine
64  */
65 void
66 init_random(void)
67 {
68         register int i;
69         register time_t now;
70
71         ran_j = 23;
72         ran_k = 54;
73
74         /*
75          * Randomize the seed array some more.  The time of day
76          * should be initialized by now.
77          */
78         now = time((time_t *)0) | 01;
79
80         for (i = 0; i < 55; ++i)
81             ran_y[i] = now * init_ran_y[i];     /* overflow does a mod */
82 }