xref: /netbsd-src/external/lgpl3/gmp/dist/mpz/tdiv_q_2exp.c (revision 92e958de60c71aa0f2452bd7074cbb006fe6546b)
1 /* mpz_tdiv_q_2exp -- Divide an integer by 2**CNT.  Round the quotient
2    towards -infinity.
3 
4 Copyright 1991, 1993, 1994, 1996, 2001, 2002, 2012 Free Software Foundation,
5 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 3 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.  If not, see http://www.gnu.org/licenses/.  */
21 
22 #include "gmp.h"
23 #include "gmp-impl.h"
24 
25 void
26 mpz_tdiv_q_2exp (mpz_ptr r, mpz_srcptr u, mp_bitcnt_t cnt)
27 {
28   mp_size_t un, rn;
29   mp_size_t limb_cnt;
30   mp_ptr rp;
31   mp_srcptr up;
32 
33   un = SIZ(u);
34   limb_cnt = cnt / GMP_NUMB_BITS;
35   rn = ABS (un) - limb_cnt;
36 
37   if (rn <= 0)
38     rn = 0;
39   else
40     {
41       rp = MPZ_REALLOC (r, rn);
42       up = PTR(u) + limb_cnt;
43 
44       cnt %= GMP_NUMB_BITS;
45       if (cnt != 0)
46 	{
47 	  mpn_rshift (rp, up, rn, cnt);
48 	  rn -= rp[rn - 1] == 0;
49 	}
50       else
51 	{
52 	  MPN_COPY_INCR (rp, up, rn);
53 	}
54     }
55 
56   SIZ(r) = un >= 0 ? rn : -rn;
57 }
58