beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpz / cong_ui.c
bloba9729d9a85892a70b775e51de50d1437cf09347c
1 /* mpz_congruent_ui_p -- test congruence of mpz and ulong.
3 Copyright 2000-2002, 2012 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
18 later version.
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
25 for more details.
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/. */
31 #include "gmp.h"
32 #include "gmp-impl.h"
33 #include "longlong.h"
36 /* There's some explicit checks for c<d since it seems reasonably likely an
37 application might use that in a test.
39 Hopefully the compiler can generate something good for r==(c%d), though
40 if modexact is being used exclusively then that's not reached. */
42 int
43 mpz_congruent_ui_p (mpz_srcptr a, unsigned long cu, unsigned long du)
45 mp_srcptr ap;
46 mp_size_t asize;
47 mp_limb_t c, d, r;
49 if (UNLIKELY (du == 0))
50 return (mpz_cmp_ui (a, cu) == 0);
52 asize = SIZ(a);
53 if (asize == 0)
55 if (cu < du)
56 return cu == 0;
57 else
58 return (cu % du) == 0;
61 /* For nails don't try to be clever if c or d is bigger than a limb, just
62 fake up some mpz_t's and go to the main mpz_congruent_p. */
63 if (du > GMP_NUMB_MAX || cu > GMP_NUMB_MAX)
65 mp_limb_t climbs[2], dlimbs[2];
66 mpz_t cz, dz;
68 ALLOC(cz) = 2;
69 PTR(cz) = climbs;
70 ALLOC(dz) = 2;
71 PTR(dz) = dlimbs;
73 mpz_set_ui (cz, cu);
74 mpz_set_ui (dz, du);
75 return mpz_congruent_p (a, cz, dz);
78 /* NEG_MOD works on limbs, so convert ulong to limb */
79 c = cu;
80 d = du;
82 if (asize < 0)
84 asize = -asize;
85 NEG_MOD (c, c, d);
88 ap = PTR (a);
90 if (ABOVE_THRESHOLD (asize, BMOD_1_TO_MOD_1_THRESHOLD))
92 r = mpn_mod_1 (ap, asize, d);
93 if (c < d)
94 return r == c;
95 else
96 return r == (c % d);
99 if ((d & 1) == 0)
101 /* Strip low zero bits to get odd d required by modexact. If
102 d==e*2^n then a==c mod d if and only if both a==c mod 2^n
103 and a==c mod e. */
105 unsigned twos;
107 if ((ap[0]-c) & LOW_ZEROS_MASK (d))
108 return 0;
110 count_trailing_zeros (twos, d);
111 d >>= twos;
114 r = mpn_modexact_1c_odd (ap, asize, d, c);
115 return r == 0 || r == d;