xref: /netbsd-src/external/lgpl3/gmp/dist/mpq/md_2exp.c (revision 212397c69a103ae7e5eafa8731ddfae671d2dee7)
1 /* mpq_mul_2exp, mpq_div_2exp - multiply or divide by 2^N */
2 
3 /*
4 Copyright 2000, 2002, 2012 Free Software Foundation, Inc.
5 
6 This file is part of the GNU MP Library.
7 
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 3 of the License, or (at your
11 option) any later version.
12 
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.
17 
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
20 
21 #include "gmp.h"
22 #include "gmp-impl.h"
23 #include "longlong.h"
24 
25 
26 /* The multiplier/divisor "n", representing 2^n, is applied by right shifting
27    "r" until it's odd (if it isn't already), and left shifting "l" for the
28    rest. */
29 
30 static void
31 mord_2exp (mpz_ptr ldst, mpz_ptr rdst, mpz_srcptr lsrc, mpz_srcptr rsrc,
32            mp_bitcnt_t n)
33 {
34   mp_size_t  rsrc_size = SIZ(rsrc);
35   mp_size_t  len = ABS (rsrc_size);
36   mp_ptr     rsrc_ptr = PTR(rsrc);
37   mp_ptr     p, rdst_ptr;
38   mp_limb_t  plow;
39 
40   p = rsrc_ptr;
41   plow = *p;
42   while (n >= GMP_NUMB_BITS && plow == 0)
43     {
44       n -= GMP_NUMB_BITS;
45       p++;
46       plow = *p;
47     }
48 
49   /* no realloc here if rsrc==rdst, so p and rsrc_ptr remain valid */
50   len -= (p - rsrc_ptr);
51   rdst_ptr = MPZ_REALLOC (rdst, len);
52 
53   if ((plow & 1) || n == 0)
54     {
55       /* need INCR when src==dst */
56       if (p != rdst_ptr)
57         MPN_COPY_INCR (rdst_ptr, p, len);
58     }
59   else
60     {
61       unsigned long  shift;
62       if (plow == 0)
63         shift = n;
64       else
65         {
66           count_trailing_zeros (shift, plow);
67           shift = MIN (shift, n);
68         }
69       mpn_rshift (rdst_ptr, p, len, shift);
70       len -= (rdst_ptr[len-1] == 0);
71       n -= shift;
72     }
73   SIZ(rdst) = (rsrc_size >= 0) ? len : -len;
74 
75   if (n)
76     mpz_mul_2exp (ldst, lsrc, n);
77   else if (ldst != lsrc)
78     mpz_set (ldst, lsrc);
79 }
80 
81 
82 void
83 mpq_mul_2exp (mpq_ptr dst, mpq_srcptr src, mp_bitcnt_t n)
84 {
85   mord_2exp (NUM(dst), DEN(dst), NUM(src), DEN(src), n);
86 }
87 
88 void
89 mpq_div_2exp (mpq_ptr dst, mpq_srcptr src, mp_bitcnt_t n)
90 {
91   if (SIZ(NUM(src)) == 0)
92     {
93       SIZ(NUM(dst)) = 0;
94       SIZ(DEN(dst)) = 1;
95       PTR(DEN(dst))[0] = 1;
96       return;
97     }
98 
99   mord_2exp (DEN(dst), NUM(dst), DEN(src), NUM(src), n);
100 }
101