xref: /netbsd/external/lgpl3/mpfr/dist/src/odd_p.c (revision 606004a0)
1 /* mpfr_odd_p -- check for odd integers
2 
3 Copyright 2001-2023 Free Software Foundation, Inc.
4 Contributed by the AriC and Caramba projects, INRIA.
5 
6 This file is part of the GNU MPFR Library.
7 
8 The GNU MPFR 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 MPFR 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 MPFR Library; see the file COPYING.LESSER.  If not, see
20 https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
21 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
22 
23 #define MPFR_NEED_LONGLONG_H
24 #include "mpfr-impl.h"
25 
26 /* Return 1 if y is an odd integer, 0 otherwise.
27    Assumes y is not singular. */
28 int
mpfr_odd_p(mpfr_srcptr y)29 mpfr_odd_p (mpfr_srcptr y)
30 {
31   mpfr_exp_t expo;
32   mpfr_prec_t prec;
33   mp_size_t yn;
34   mp_limb_t *yp;
35 
36   /* NAN, INF or ZERO are not allowed */
37   MPFR_ASSERTD (!MPFR_IS_SINGULAR (y));
38 
39   expo = MPFR_GET_EXP (y);
40   if (expo <= 0)
41     return 0;  /* |y| < 1 and not 0 */
42 
43   prec = MPFR_PREC(y);
44   if ((mpfr_prec_t) expo > prec)
45     return 0;  /* y is a multiple of 2^(expo-prec), thus not odd */
46 
47   /* 0 < expo <= prec:
48      y = 1xxxxxxxxxt.zzzzzzzzzzzzzzzzzz[000]
49           expo bits   (prec-expo) bits
50 
51      We have to check that:
52      (a) the bit 't' is set
53      (b) all the 'z' bits are zero
54   */
55 
56   prec = MPFR_PREC2LIMBS (prec) * GMP_NUMB_BITS - expo;
57   /* number of z+0 bits */
58 
59   yn = prec / GMP_NUMB_BITS;
60   MPFR_ASSERTN(yn >= 0);
61   /* yn is the index of limb containing the 't' bit */
62 
63   yp = MPFR_MANT(y);
64   /* if expo is a multiple of GMP_NUMB_BITS, t is bit 0 */
65   if (expo % GMP_NUMB_BITS == 0 ? (yp[yn] & 1) == 0
66       : MPFR_LIMB_LSHIFT(yp[yn], (expo % GMP_NUMB_BITS) - 1) != MPFR_LIMB_HIGHBIT)
67     return 0;
68   while (--yn >= 0)
69     if (yp[yn] != 0)
70       return 0;
71   return 1;
72 }
73 
74