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 either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
20 or both in parallel, as here.
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library. If not,
29 see https://www.gnu.org/licenses/. */
32 #include "mini-gmp/mini-gmp.c"
34 #define MIN(l,o) ((l) < (o) ? (l) : (o))
35 #define PTR(x) ((x)->_mp_d)
36 #define SIZ(x) ((x)->_mp_size)
38 #define xmalloc gmp_default_alloc
41 isprime (unsigned long int t)
43 unsigned long int q, r, d;
46 return (0xa08a28acUL >> t) & 1;
88 /* Set inv to the inverse of d, in the style of invert_limb, ie. for
91 mpz_preinv_invert (mpz_t inv, mpz_t d, int numb_bits)
97 norm = numb_bits - mpz_sizeinbase (d, 2);
99 mpz_init_set_ui (t, 1L);
100 mpz_mul_2exp (t, t, 2*numb_bits - norm);
101 mpz_tdiv_q (inv, t, d);
103 mpz_mul_2exp (t, t, numb_bits);
104 mpz_sub (inv, inv, t);
109 /* Calculate r satisfying r*d == 1 mod 2^n. */
111 mpz_invert_2exp (mpz_t r, mpz_t a, unsigned long n)
116 assert (mpz_odd_p (a));
118 mpz_init_set_ui (inv, 1L);
121 for (i = 1; i < n; i++)
123 mpz_mul (prod, inv, a);
124 if (mpz_tstbit (prod, i) != 0)
128 mpz_mul (prod, inv, a);
129 mpz_tdiv_r_2exp (prod, prod, n);
130 assert (mpz_cmp_ui (prod, 1L) == 0);
138 /* Calculate inv satisfying r*a == 1 mod 2^n. */
140 mpz_invert_ui_2exp (mpz_t r, unsigned long a, unsigned long n)
143 mpz_init_set_ui (az, a);
144 mpz_invert_2exp (r, az, n);