1 /* mpz_fdiv_r_2exp -- Divide a integer by 2**CNT and produce a remainder.
3 Copyright (C) 1991, 1993, 1994, 1995, 1998, 1999, 2000 Free Software
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 */
88 MPZ_TMP_INIT (tmp, cnt/BITS_PER_MP_LIMB + 2);
90 mpz_mul_2exp (tmp, tmp, cnt);
91 mpz_sub (res, tmp, res);
96 /* This is an alternative ending of the above function using just low-level
97 functions. Tested, but perhaps excessive? */
99 if (in->_mp_size < 0 && res_size != 0)
101 /* Result should be 2^CNT - RES */
105 limb_cnt = cnt / BITS_PER_MP_LIMB;
107 if (res->_mp_alloc <= limb_cnt)
108 _mpz_realloc (res, limb_cnt + 1);
110 if (res_size > limb_cnt)
112 mpn_nz_neg (rp, rp, res_size);
113 rp[limb_cnt] &= ~(~(mp_limb_t) 0 << cnt % BITS_PER_MP_LIMB);
114 MPN_NORMALIZE_NOT_ZERO (rp, res_size);
119 mpn_nz_neg (rp, rp, res_size);
120 for (i = res_size; i < limb_cnt; i++)
121 rp[i] = ~ (mp_limb_t) 0;
123 if (cnt % BITS_PER_MP_LIMB != 0)
125 rp[res_size] = ((mp_limb_t) 1 << (cnt % BITS_PER_MP_LIMB)) - 1;
129 MPN_NORMALIZE_NOT_ZERO (rp, res_size);
136 mpn_nz_neg (rp, sp, n)
145 for (i = 1; x == 0; i++)