1 /* mpz_divexact_gcd -- exact division optimized for GCDs.
3 THE FUNCTIONS IN THIS FILE ARE FOR INTERNAL USE AND ARE ALMOST CERTAIN TO
4 BE SUBJECT TO INCOMPATIBLE CHANGES IN FUTURE GNU MP RELEASES.
6 Copyright 2000, 2005, 2011, 2012 Free Software Foundation, Inc.
8 This file is part of the GNU MP Library.
10 The GNU MP Library is free software; you can redistribute it and/or modify
11 it under the terms of either:
13 * the GNU Lesser General Public License as published by the Free
14 Software Foundation; either version 3 of the License, or (at your
15 option) any later version.
19 * the GNU General Public License as published by the Free Software
20 Foundation; either version 2 of the License, or (at your option) any
23 or both in parallel, as here.
25 The GNU MP Library is distributed in the hope that it will be useful, but
26 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
27 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
30 You should have received copies of the GNU General Public License and the
31 GNU Lesser General Public License along with the GNU MP Library. If not,
32 see https://www.gnu.org/licenses/. */
39 /* Set q to a/d, expecting d to be from a GCD and therefore usually small.
41 The distribution of GCDs of random numbers can be found in Knuth volume 2
42 section 4.5.2 theorem D.
50 Only the low limb is examined for optimizations, since GCDs bigger than
51 2^32 (or 2^64) will occur very infrequently.
53 Future: This could change to an mpn_divexact_gcd, possibly partly
54 inlined, if/when the relevant mpq functions change to an mpn based
58 #if GMP_NUMB_BITS % 2 == 0
60 mpz_divexact_by3 (mpz_ptr q
, mpz_srcptr a
)
62 mp_size_t size
= SIZ(a
);
63 mp_size_t abs_size
= ABS(size
);
66 qp
= MPZ_REALLOC (q
, abs_size
);
68 mpn_bdiv_dbm1 (qp
, PTR(a
), abs_size
, GMP_NUMB_MASK
/ 3);
70 abs_size
-= (qp
[abs_size
-1] == 0);
71 SIZ(q
) = (size
>0 ? abs_size
: -abs_size
);
75 #if GMP_NUMB_BITS % 4 == 0
77 mpz_divexact_by5 (mpz_ptr q
, mpz_srcptr a
)
79 mp_size_t size
= SIZ(a
);
80 mp_size_t abs_size
= ABS(size
);
83 qp
= MPZ_REALLOC (q
, abs_size
);
85 mpn_bdiv_dbm1 (qp
, PTR(a
), abs_size
, GMP_NUMB_MASK
/ 5);
87 abs_size
-= (qp
[abs_size
-1] == 0);
88 SIZ(q
) = (size
>0 ? abs_size
: -abs_size
);
93 mpz_divexact_limb (mpz_ptr q
, mpz_srcptr a
, mp_limb_t d
)
95 mp_size_t size
= SIZ(a
);
96 mp_size_t abs_size
= ABS(size
);
99 qp
= MPZ_REALLOC (q
, abs_size
);
101 mpn_divexact_1 (qp
, PTR(a
), abs_size
, d
);
103 abs_size
-= (qp
[abs_size
-1] == 0);
104 SIZ(q
) = (size
>0 ? abs_size
: -abs_size
);
108 mpz_divexact_gcd (mpz_ptr q
, mpz_srcptr a
, mpz_srcptr d
)
110 ASSERT (mpz_sgn (d
) > 0);
120 mp_limb_t dl
= PTR(d
)[0];
125 count_trailing_zeros (twos
, dl
);
127 mpz_tdiv_q_2exp (q
, a
, twos
);
137 #if GMP_NUMB_BITS % 2 == 0
140 mpz_divexact_by3 (q
, a
);
144 #if GMP_NUMB_BITS % 4 == 0
147 mpz_divexact_by5 (q
, a
);
152 mpz_divexact_limb (q
, a
, dl
);
156 mpz_divexact (q
, a
, d
);