github.com/aergoio/aergo@v1.3.1/libtool/src/gmp-6.1.2/rand/randmui.c (about) 1 /* gmp_urandomm_ui -- uniform random number 0 to N-1 for ulong N. 2 3 Copyright 2003, 2004 Free Software Foundation, Inc. 4 5 This file is part of the GNU MP Library. 6 7 The GNU MP Library is free software; you can redistribute it and/or modify 8 it under the terms of either: 9 10 * the GNU Lesser General Public License as published by the Free 11 Software Foundation; either version 3 of the License, or (at your 12 option) any later version. 13 14 or 15 16 * the GNU General Public License as published by the Free Software 17 Foundation; either version 2 of the License, or (at your option) any 18 later version. 19 20 or both in parallel, as here. 21 22 The GNU MP Library is distributed in the hope that it will be useful, but 23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 25 for more details. 26 27 You should have received copies of the GNU General Public License and the 28 GNU Lesser General Public License along with the GNU MP Library. If not, 29 see https://www.gnu.org/licenses/. */ 30 31 #include "gmp.h" 32 #include "gmp-impl.h" 33 #include "longlong.h" 34 35 36 /* If n is a power of 2 then the test ret<n is always true and the loop is 37 unnecessary, but there's no need to add special code for this. Just get 38 the "bits" calculation correct and let it go through normally. 39 40 If n is 1 then will have bits==0 and _gmp_rand will produce no output and 41 we always return 0. Again there seems no need for a special case, just 42 initialize a[0]=0 and let it go through normally. */ 43 44 #define MAX_URANDOMM_ITER 80 45 46 unsigned long 47 gmp_urandomm_ui (gmp_randstate_ptr rstate, unsigned long n) 48 { 49 mp_limb_t a[LIMBS_PER_ULONG]; 50 unsigned long ret, bits, leading; 51 int i; 52 53 if (UNLIKELY (n == 0)) 54 DIVIDE_BY_ZERO; 55 56 /* start with zeros, since if bits==0 then _gmp_rand will store nothing at 57 all (bits==0 arises when n==1), or if bits <= GMP_NUMB_BITS then it 58 will store only a[0]. */ 59 a[0] = 0; 60 #if LIMBS_PER_ULONG > 1 61 a[1] = 0; 62 #endif 63 64 count_leading_zeros (leading, (mp_limb_t) n); 65 bits = GMP_LIMB_BITS - leading - (POW2_P(n) != 0); 66 67 for (i = 0; i < MAX_URANDOMM_ITER; i++) 68 { 69 _gmp_rand (a, rstate, bits); 70 #if LIMBS_PER_ULONG == 1 71 ret = a[0]; 72 #else 73 ret = a[0] | (a[1] << GMP_NUMB_BITS); 74 #endif 75 if (LIKELY (ret < n)) /* usually one iteration suffices */ 76 goto done; 77 } 78 79 /* Too many iterations, there must be something degenerate about the 80 rstate algorithm. Return r%n. */ 81 ret -= n; 82 ASSERT (ret < n); 83 84 done: 85 return ret; 86 }