urandomm.c revision 1.1.1.3
1/* mpz_urandomm (rop, state, n) -- Generate a uniform pseudorandom 2 integer in the range 0 to N-1, using STATE as the random state 3 previously initialized by a call to gmp_randinit(). 4 5Copyright 2000, 2002, 2012 Free Software Foundation, Inc. 6 7This file is part of the GNU MP Library. 8 9The GNU MP Library is free software; you can redistribute it and/or modify 10it under the terms of either: 11 12 * the GNU Lesser General Public License as published by the Free 13 Software Foundation; either version 3 of the License, or (at your 14 option) any later version. 15 16or 17 18 * the GNU General Public License as published by the Free Software 19 Foundation; either version 2 of the License, or (at your option) any 20 later version. 21 22or both in parallel, as here. 23 24The GNU MP Library is distributed in the hope that it will be useful, but 25WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 26or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 27for more details. 28 29You should have received copies of the GNU General Public License and the 30GNU Lesser General Public License along with the GNU MP Library. If not, 31see https://www.gnu.org/licenses/. */ 32 33#include "gmp.h" 34#include "gmp-impl.h" 35#include "longlong.h" /* for count_leading_zeros */ 36 37 38#define MAX_URANDOMM_ITER 80 39 40void 41mpz_urandomm (mpz_ptr rop, gmp_randstate_t rstate, mpz_srcptr n) 42{ 43 mp_ptr rp, np, nlast; 44 mp_size_t nbits, size; 45 int count; 46 int pow2; 47 int cmp; 48 TMP_DECL; 49 50 size = ABSIZ (n); 51 if (UNLIKELY (size == 0)) 52 DIVIDE_BY_ZERO; 53 54 nlast = &PTR (n)[size - 1]; 55 56 /* Detect whether n is a power of 2. */ 57 pow2 = POW2_P (*nlast); 58 if (pow2 != 0) 59 for (np = PTR (n); np < nlast; np++) 60 if (*np != 0) 61 { 62 pow2 = 0; /* Mark n as `not a power of two'. */ 63 break; 64 } 65 66 count_leading_zeros (count, *nlast); 67 nbits = size * GMP_NUMB_BITS - (count - GMP_NAIL_BITS) - pow2; 68 if (nbits == 0) /* nbits == 0 means that n was == 1. */ 69 { 70 SIZ (rop) = 0; 71 return; 72 } 73 74 TMP_MARK; 75 np = PTR (n); 76 if (rop == n) 77 { 78 mp_ptr tp; 79 tp = TMP_ALLOC_LIMBS (size); 80 MPN_COPY (tp, np, size); 81 np = tp; 82 } 83 84 /* Here the allocated size can be one too much if n is a power of 85 (2^GMP_NUMB_BITS) but it's convenient for using mpn_cmp below. */ 86 rp = MPZ_REALLOC (rop, size); 87 /* Clear last limb to prevent the case in which size is one too much. */ 88 rp[size - 1] = 0; 89 90 count = MAX_URANDOMM_ITER; /* Set iteration count limit. */ 91 do 92 { 93 _gmp_rand (rp, rstate, nbits); 94 MPN_CMP (cmp, rp, np, size); 95 } 96 while (cmp >= 0 && --count != 0); 97 98 if (count == 0) 99 /* Too many iterations; return result mod n == result - n */ 100 mpn_sub_n (rp, rp, np, size); 101 102 MPN_NORMALIZE (rp, size); 103 SIZ (rop) = size; 104 TMP_FREE; 105} 106