1/*****************************************************************************
2
3Copyright (c) 1994, 2016, Oracle and/or its affiliates. All Rights Reserved.
4
5This program is free software; you can redistribute it and/or modify it under
6the terms of the GNU General Public License as published by the Free Software
7Foundation; version 2 of the License.
8
9This program is distributed in the hope that it will be useful, but WITHOUT
10ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12
13You should have received a copy of the GNU General Public License along with
14this program; if not, write to the Free Software Foundation, Inc.,
1551 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
16
17*****************************************************************************/
18
19/***************************************************************//**
20@file ut/ut0rnd.cc
21Random numbers and hashing
22
23Created 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(). */
36ulint ut_rnd_ulint_counter = 65654363;
37
38/***********************************************************//**
39Looks for a prime number slightly greater than the given argument.
40The prime is chosen so that it is not near any power of 2.
41@return prime */
42ulint
43ut_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;
88next_n: ;
89 }
90
91 return(n);
92}
93