1 /* mpz_congruent_2exp_p -- test congruence of mpz mod 2^n.
3 Copyright 2001, 2002, 2013 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
20 or both in parallel, as here.
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library. If not,
29 see https://www.gnu.org/licenses/. */
36 mpz_congruent_2exp_p (mpz_srcptr a
, mpz_srcptr c
, mp_bitcnt_t d
) __GMP_NOTHROW
41 mp_limb_t dmask
, alimb
, climb
, sum
;
42 mp_size_t as
, cs
, asize
, csize
;
52 MPZ_SRCPTR_SWAP (a
, c
);
53 MP_SIZE_T_SWAP (asize
, csize
);
56 dlimbs
= d
/ GMP_NUMB_BITS
;
57 dbits
= d
% GMP_NUMB_BITS
;
58 dmask
= (CNST_LIMB(1) << dbits
) - 1;
68 /* same signs, direct comparison */
70 /* a==c for limbs in common */
71 if (mpn_cmp (ap
, cp
, MIN (csize
, dlimbs
)) != 0)
74 /* if that's all of dlimbs, then a==c for remaining bits */
76 return ((ap
[dlimbs
]-cp
[dlimbs
]) & dmask
) == 0;
79 /* a remains, need all zero bits */
81 /* if d covers all of a and c, then must be exactly equal */
83 return asize
== csize
;
85 /* whole limbs zero */
86 for (i
= csize
; i
< dlimbs
; i
++)
90 /* partial limb zero */
91 return (ap
[dlimbs
] & dmask
) == 0;
95 /* different signs, negated comparison */
97 /* common low zero limbs, stopping at first non-zeros, which must
98 match twos complement */
102 ASSERT (i
< csize
); /* always have a non-zero limb on c */
105 sum
= (alimb
+ climb
) & GMP_NUMB_MASK
;
108 return (sum
& dmask
) == 0;
111 /* require both zero, or first non-zeros as twos-complements */
114 } while (alimb
== 0);
116 /* further limbs matching as ones-complement */
117 for (; i
< csize
; ++i
)
121 sum
= alimb
^ climb
^ GMP_NUMB_MASK
;
124 return (sum
& dmask
) == 0;
130 /* no more c, so require all 1 bits in a */
133 return 0; /* not enough a */
136 for ( ; i
< dlimbs
; i
++)
137 if (ap
[i
] != GMP_NUMB_MAX
)
140 /* if only whole limbs, no further fetches from a */
148 return ((ap
[dlimbs
]+1) & dmask
) == 0;