Annotation of OpenXM_contrib/gmp/mpz/urandomm.c, Revision 1.1.1.1
1.1 maekawa 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:
5: Copyright (C) 2000 Free Software Foundation, Inc.
6:
7: This file is part of the GNU MP Library.
8:
9: The GNU MP Library is free software; you can redistribute it and/or modify
10: it under the terms of the GNU Lesser General Public License as published by
11: the Free Software Foundation; either version 2.1 of the License, or (at your
12: option) any later version.
13:
14: The GNU MP Library is distributed in the hope that it will be useful, but
15: WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16: or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
17: License for more details.
18:
19: You should have received a copy of the GNU Lesser General Public License
20: along with the GNU MP Library; see the file COPYING.LIB. If not, write to
21: the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22: MA 02111-1307, USA. */
23:
24: #include "gmp.h"
25: #include "gmp-impl.h"
26: #include "longlong.h"
27:
28: void
29: #if __STDC__
30: mpz_urandomm (mpz_t rop, gmp_randstate_t rstate, mpz_t n)
31: #else
32: mpz_urandomm (rop, rstate, n)
33: mpz_t rop;
34: gmp_randstate_t rstate;
35: mpz_t n;
36: #endif
37: {
38: mpz_t t, p, m;
39: mp_ptr tp;
40: mp_size_t nbits, size;
41: int count;
42:
43: /* FIXME: Should check for n == 0 and report error */
44:
45: size = SIZ (n);
46: count_leading_zeros (count, PTR (n)[size - 1]);
47: nbits = size * BITS_PER_MP_LIMB - count;
48:
49: /* Allocate enough for any mpz function called since a realloc of
50: these will fail. */
51: MPZ_TMP_INIT (t, size);
52: MPZ_TMP_INIT (m, size + 1);
53: MPZ_TMP_INIT (p, size + 1);
54:
55: /* Let m = highest possible random number plus 1. */
56: mpz_set_ui (m, 0);
57: mpz_setbit (m, nbits);
58:
59: /* Let p = floor(m / n) * n. */
60: mpz_fdiv_q (p, m, n);
61: mpz_mul (p, p, n);
62:
63: tp = PTR (t);
64: do
65: {
66: _gmp_rand (tp, rstate, nbits);
67: MPN_NORMALIZE (tp, size); /* FIXME: Really necessary? */
68: SIZ (t) = size;
69: }
70: while (mpz_cmp (t, p) >= 0);
71:
72: mpz_mod (rop, t, n);
73: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>