~ubuntu-branches/ubuntu/quantal/gclcvs/quantal

« back to all changes in this revision

Viewing changes to gmp3/mpz/urandomm.c

  • Committer: Bazaar Package Importer
  • Author(s): Camm Maguire
  • Date: 2004-06-24 15:13:46 UTC
  • Revision ID: james.westby@ubuntu.com-20040624151346-xh0xaaktyyp7aorc
Tags: 2.7.0-26
C_GC_OFFSET is 2 on m68k-linux

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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 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
mpz_urandomm (mpz_ptr rop, gmp_randstate_t rstate, mpz_srcptr n)
 
30
{
 
31
  mpz_t t, p, m;
 
32
  mp_ptr tp;
 
33
  mp_size_t nbits, size;
 
34
  int count;
 
35
  TMP_DECL (marker);
 
36
 
 
37
  TMP_MARK (marker);
 
38
 
 
39
  /* FIXME: Should check for n == 0 and report error */
 
40
 
 
41
  size = SIZ (n);
 
42
  count_leading_zeros (count, PTR (n)[size - 1]);
 
43
  nbits = size * BITS_PER_MP_LIMB - count;
 
44
 
 
45
  /* Allocate enough for any mpz function called since a realloc of
 
46
     these will fail.  */
 
47
  MPZ_TMP_INIT (t, size);
 
48
  MPZ_TMP_INIT (m, size + 1);
 
49
  MPZ_TMP_INIT (p, size + 1);
 
50
 
 
51
  /* Let m = highest possible random number plus 1.  */
 
52
  mpz_set_ui (m, 0);
 
53
  mpz_setbit (m, nbits);
 
54
 
 
55
  /* Let p = floor(m / n) * n.  */
 
56
  mpz_fdiv_q (p, m, n);
 
57
  mpz_mul (p, p, n);
 
58
 
 
59
  tp = PTR (t);
 
60
  do
 
61
    {
 
62
      _gmp_rand (tp, rstate, nbits);
 
63
      MPN_NORMALIZE (tp, size); /* FIXME: Really necessary?  */
 
64
      SIZ (t) = size;
 
65
    }
 
66
  while (mpz_cmp (t, p) >= 0);
 
67
 
 
68
  mpz_mod (rop, t, n);
 
69
 
 
70
  TMP_FREE (marker);
 
71
}