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