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