1 /* mpz_congruent_2exp_p -- test congruence of mpz mod 2^n.
3 Copyright 2001, 2002 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 the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
12 The GNU MP Library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */
25 mpz_congruent_2exp_p (mpz_srcptr a, mpz_srcptr c, unsigned long d)
27 unsigned long i, dlimbs, dbits;
29 mp_limb_t dmask, alimb, climb, sum;
30 mp_size_t asize_signed, csize_signed, asize, csize;
32 if (ABSIZ(a) < ABSIZ(c))
33 MPZ_SRCPTR_SWAP (a, c);
35 dlimbs = d / GMP_NUMB_BITS;
36 dbits = d % GMP_NUMB_BITS;
37 dmask = (CNST_LIMB(1) << dbits) - 1;
42 asize_signed = SIZ(a);
43 asize = ABS(asize_signed);
45 csize_signed = SIZ(c);
46 csize = ABS(csize_signed);
48 if (csize_signed == 0)
51 if ((asize_signed ^ csize_signed) >= 0)
53 /* same signs, direct comparison */
55 /* a==c for limbs in common */
56 if (mpn_cmp (ap, cp, MIN (csize, dlimbs)) != 0)
59 /* if that's all of dlimbs, then a==c for remaining bits */
61 return ((ap[dlimbs]-cp[dlimbs]) & dmask) == 0;
64 /* a remains, need all zero bits */
66 /* if d covers all of a and c, then must be exactly equal */
68 return asize == csize;
70 /* whole limbs zero */
71 for (i = csize; i < dlimbs; i++)
75 /* partial limb zero */
76 return (ap[dlimbs] & dmask) == 0;
80 /* different signs, negated comparison */
82 /* common low zero limbs, stopping at first non-zeros, which must
83 match twos complement */
87 ASSERT (i < csize); /* always have a non-zero limb on c */
90 sum = (alimb + climb) & GMP_NUMB_MASK;
93 return (sum & dmask) == 0;
96 /* require both zero, or first non-zeros as twos-complements */
104 /* further limbs matching as ones-complement */
112 sum = (alimb + climb + 1) & GMP_NUMB_MASK;
115 return (sum & dmask) == 0;
123 /* no more c, so require all 1 bits in a */
126 return 0; /* not enough a */
129 for ( ; i < dlimbs; i++)
130 if (ap[i] != GMP_NUMB_MAX)
133 /* if only whole limbs, no further fetches from a */
141 return ((ap[dlimbs]+1) & dmask) == 0;