1 /* Functions needed for bootstrapping the gmp build, based on mini-gmp.
3 Copyright 2001, 2002, 2004, 2011, 2012 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
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.
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.
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/. */
21 #include "mini-gmp/mini-gmp.c"
23 #define MIN(l,o) ((l) < (o) ? (l) : (o))
24 #define PTR(x) ((x)->_mp_d)
25 #define SIZ(x) ((x)->_mp_size)
27 #define xmalloc gmp_default_alloc
30 isprime (unsigned long int t)
32 unsigned long int q, r, d;
35 return (0xa08a28acUL >> t) & 1;
77 /* Set inv to the inverse of d, in the style of invert_limb, ie. for
80 mpz_preinv_invert (mpz_t inv, mpz_t d, int numb_bits)
86 norm = numb_bits - mpz_sizeinbase (d, 2);
88 mpz_init_set_ui (t, 1L);
89 mpz_mul_2exp (t, t, 2*numb_bits - norm);
90 mpz_tdiv_q (inv, t, d);
92 mpz_mul_2exp (t, t, numb_bits);
93 mpz_sub (inv, inv, t);
98 /* Calculate r satisfying r*d == 1 mod 2^n. */
100 mpz_invert_2exp (mpz_t r, mpz_t a, unsigned long n)
105 assert (mpz_odd_p (a));
107 mpz_init_set_ui (inv, 1L);
110 for (i = 1; i < n; i++)
112 mpz_mul (prod, inv, a);
113 if (mpz_tstbit (prod, i) != 0)
117 mpz_mul (prod, inv, a);
118 mpz_tdiv_r_2exp (prod, prod, n);
119 assert (mpz_cmp_ui (prod, 1L) == 0);
127 /* Calculate inv satisfying r*a == 1 mod 2^n. */
129 mpz_invert_ui_2exp (mpz_t r, unsigned long a, unsigned long n)
132 mpz_init_set_ui (az, a);
133 mpz_invert_2exp (r, az, n);