1 /*****************************************************************************
2 
3 Copyright (c) 1994, 2016, Oracle and/or its affiliates. All Rights Reserved.
4 Copyright (c) 2019, MariaDB Corporation.
5 
6 This program is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free Software
8 Foundation; version 2 of the License.
9 
10 This program is distributed in the hope that it will be useful, but WITHOUT
11 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
13 
14 You should have received a copy of the GNU General Public License along with
15 this program; if not, write to the Free Software Foundation, Inc.,
16 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
17 
18 *****************************************************************************/
19 
20 /***************************************************************//**
21 @file ut/ut0rnd.cc
22 Random numbers and hashing
23 
24 Created 5/11/1994 Heikki Tuuri
25 ********************************************************************/
26 
27 #include "ut0rnd.h"
28 
29 /** Seed value of ut_rnd_gen() */
30 int32 ut_rnd_current;
31 
32 /** These random numbers are used in ut_find_prime */
33 /*@{*/
34 #define	UT_RANDOM_1	1.0412321
35 #define	UT_RANDOM_2	1.1131347
Status()36 #define UT_RANDOM_3	1.0132677
37 /*@}*/
38 
39 /***********************************************************//**
40 Looks for a prime number slightly greater than the given argument.
41 The prime is chosen so that it is not near any power of 2.
42 @return prime */
43 ulint
44 ut_find_prime(
45 /*==========*/
46 	ulint	n)	/*!< in: positive number > 100 */
47 {
48 	ulint	pow2;
49 	ulint	i;
50 
51 	n += 100;
52 
53 	pow2 = 1;
54 	while (pow2 * 2 < n) {
55 		pow2 = 2 * pow2;
56 	}
57 
58 	if ((double) n < 1.05 * (double) pow2) {
59 		n = (ulint) ((double) n * UT_RANDOM_1);
60 	}
61 
62 	pow2 = 2 * pow2;
63 
64 	if ((double) n > 0.95 * (double) pow2) {
65 		n = (ulint) ((double) n * UT_RANDOM_2);
66 	}
67 
68 	if (n > pow2 - 20) {
69 		n += 30;
70 	}
71 
72 	/* Now we have n far enough from powers of 2. To make
73 	n more random (especially, if it was not near
74 	a power of 2), we then multiply it by a random number. */
75 
76 	n = (ulint) ((double) n * UT_RANDOM_3);
77 
78 	for (;; n++) {
79 		i = 2;
80 		while (i * i <= n) {
81 			if (n % i == 0) {
82 				goto next_n;
83 			}
84 			i++;
85 		}
86 
87 		/* Found a prime */
88 		break;
89 next_n:		;
90 	}
91 
92 	return(n);
93 }
94