You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.3 KiB

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