tizen 2.3 release
[external/gmp.git] / randmui.c
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 2.1 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; see the file COPYING.LIB.  If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 MA 02110-1301, USA. */
21
22 #include "gmp.h"
23 #include "gmp-impl.h"
24 #include "longlong.h"
25
26
27 /* If n is a power of 2 then the test ret<n is always true and the loop is
28    unnecessary, but there's no need to add special code for this.  Just get
29    the "bits" calculation correct and let it go through normally.
30
31    If n is 1 then will have bits==0 and _gmp_rand will produce no output and
32    we always return 0.  Again there seems no need for a special case, just
33    initialize a[0]=0 and let it go through normally.  */
34
35 #define MAX_URANDOMM_ITER  80
36
37 unsigned long
38 gmp_urandomm_ui (gmp_randstate_ptr rstate, unsigned long n)
39 {
40   mp_limb_t      a[LIMBS_PER_ULONG];
41   unsigned long  ret, bits, leading;
42   int            i;
43
44   if (UNLIKELY (n == 0))
45     DIVIDE_BY_ZERO;
46
47   /* start with zeros, since if bits==0 then _gmp_rand will store nothing at
48      all (bits==0 arises when n==1), or if bits <= GMP_NUMB_BITS then it
49      will store only a[0].  */
50   a[0] = 0;
51 #if LIMBS_PER_ULONG > 1
52   a[1] = 0;
53 #endif
54
55   count_leading_zeros (leading, (mp_limb_t) n);
56   bits = GMP_LIMB_BITS - leading - (POW2_P(n) != 0);
57
58   for (i = 0; i < MAX_URANDOMM_ITER; i++)
59     {
60       _gmp_rand (a, rstate, bits);
61 #if LIMBS_PER_ULONG == 1
62       ret = a[0];
63 #else
64       ret = a[0] | (a[1] << GMP_NUMB_BITS);
65 #endif
66       if (LIKELY (ret < n))   /* usually one iteration suffices */
67         goto done;
68     }
69
70   /* Too many iterations, there must be something degenerate about the
71      rstate algorithm.  Return r%n.  */
72   ret -= n;
73   ASSERT (ret < n);
74
75  done:
76   return ret;
77 }