blob: b24c7dc74b082821fb2f5771b2580bcaf5438054 [file] [log] [blame]
Austin Schuhdace2a62020-08-18 10:56:48 -07001/* mpz_divisible_ui_p -- mpz by ulong divisibility test.
2
3Copyright 2000-2002 Free Software Foundation, Inc.
4
5This file is part of the GNU MP Library.
6
7The GNU MP Library is free software; you can redistribute it and/or modify
8it under the terms of either:
9
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.
13
14or
15
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.
19
20or both in parallel, as here.
21
22The GNU MP Library is distributed in the hope that it will be useful, but
23WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25for more details.
26
27You should have received copies of the GNU General Public License and the
28GNU Lesser General Public License along with the GNU MP Library. If not,
29see https://www.gnu.org/licenses/. */
30
31#include "gmp-impl.h"
32#include "longlong.h"
33
34
35int
36mpz_divisible_ui_p (mpz_srcptr a, unsigned long d)
37{
38 mp_size_t asize;
39 mp_ptr ap;
40 unsigned twos;
41
42 asize = SIZ(a);
43 if (UNLIKELY (d == 0))
44 return (asize == 0);
45
46 if (asize == 0) /* 0 divisible by any d */
47 return 1;
48
49 /* For nails don't try to be clever if d is bigger than a limb, just fake
50 up an mpz_t and go to the main mpz_divisible_p. */
51 if (d > GMP_NUMB_MAX)
52 {
53 mp_limb_t dlimbs[2];
54 mpz_t dz;
55 ALLOC(dz) = 2;
56 PTR(dz) = dlimbs;
57 mpz_set_ui (dz, d);
58 return mpz_divisible_p (a, dz);
59 }
60
61 ap = PTR(a);
62 asize = ABS(asize); /* ignore sign of a */
63
64 if (ABOVE_THRESHOLD (asize, BMOD_1_TO_MOD_1_THRESHOLD))
65 return mpn_mod_1 (ap, asize, (mp_limb_t) d) == 0;
66
67 if (! (d & 1))
68 {
69 /* Strip low zero bits to get odd d required by modexact. If d==e*2^n
70 and a is divisible by 2^n and by e, then it's divisible by d. */
71
72 if ((ap[0] & LOW_ZEROS_MASK (d)) != 0)
73 return 0;
74
75 count_trailing_zeros (twos, (mp_limb_t) d);
76 d >>= twos;
77 }
78
79 return mpn_modexact_1_odd (ap, asize, (mp_limb_t) d) == 0;
80}