1 /* mpz_fdiv_r_2exp -- Divide a integer by 2**CNT and produce a remainder.
3 Copyright (C) 1991, 1993, 1994, 1995, 1998, 1999 Free Software Foundation,
6 This file is part of the GNU MP Library.
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or (at your
11 option) any later version.
13 The GNU MP Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
16 License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MP Library; see the file COPYING.LIB. If not, write to
20 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21 MA 02111-1307, USA. */
28 mpz_fdiv_r_2exp (mpz_ptr res, mpz_srcptr in, unsigned long int cnt)
30 mpz_fdiv_r_2exp (res, in, cnt)
33 unsigned long int cnt;
36 mp_size_t in_size = ABS (in->_mp_size);
38 mp_size_t limb_cnt = cnt / BITS_PER_MP_LIMB;
39 mp_srcptr in_ptr = in->_mp_d;
41 if (in_size > limb_cnt)
43 /* The input operand is (probably) greater than 2**CNT. */
46 x = in_ptr[limb_cnt] & (((mp_limb_t) 1 << cnt % BITS_PER_MP_LIMB) - 1);
49 res_size = limb_cnt + 1;
50 if (res->_mp_alloc < res_size)
51 _mpz_realloc (res, res_size);
53 res->_mp_d[limb_cnt] = x;
58 MPN_NORMALIZE (in_ptr, res_size);
60 if (res->_mp_alloc < res_size)
61 _mpz_realloc (res, res_size);
68 /* The input operand is smaller than 2**CNT. We perform a no-op,
69 apart from that we might need to copy IN to RES, and may need
70 to round the result. */
72 if (res->_mp_alloc < res_size)
73 _mpz_realloc (res, res_size);
79 MPN_COPY (res->_mp_d, in->_mp_d, limb_cnt);
80 in_size = in->_mp_size;
81 res->_mp_size = res_size;
82 if (in_size < 0 && res_size != 0)
84 /* Result should be 2^CNT - RES */
86 MPZ_TMP_INIT (tmp, cnt/BITS_PER_MP_LIMB + 2);
88 mpz_mul_2exp (tmp, tmp, cnt);
89 mpz_sub (res, tmp, res);
93 /* This is an alternative ending of the above function using just low-level
94 functions. Tested, but perhaps excessive? */
96 if (in->_mp_size < 0 && res_size != 0)
98 /* Result should be 2^CNT - RES */
102 limb_cnt = cnt / BITS_PER_MP_LIMB;
104 if (res->_mp_alloc <= limb_cnt)
105 _mpz_realloc (res, limb_cnt + 1);
107 if (res_size > limb_cnt)
109 mpn_nz_neg (rp, rp, res_size);
110 rp[limb_cnt] &= ~(~(mp_limb_t) 0 << cnt % BITS_PER_MP_LIMB);
111 MPN_NORMALIZE_NOT_ZERO (rp, res_size);
116 mpn_nz_neg (rp, rp, res_size);
117 for (i = res_size; i < limb_cnt; i++)
118 rp[i] = ~ (mp_limb_t) 0;
120 if (cnt % BITS_PER_MP_LIMB != 0)
122 rp[res_size] = ((mp_limb_t) 1 << (cnt % BITS_PER_MP_LIMB)) - 1;
126 MPN_NORMALIZE_NOT_ZERO (rp, res_size);
133 mpn_nz_neg (rp, sp, n)
142 for (i = 1; x == 0; i++)