1 /* mpz_tdiv_q -- divide two integers and produce a quotient.
3 Copyright (C) 1991, 1993, 1994, 1996 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 Library General Public License as published by
9 the Free Software Foundation; either version 2 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 Library General Public
15 License for more details.
17 You should have received a copy of the GNU Library General Public License
18 along with the GNU MP Library; see the file COPYING.LIB. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20 MA 02111-1307, USA. */
28 mpz_tdiv_q (mpz_ptr quot, mpz_srcptr num, mpz_srcptr den)
30 mpz_tdiv_q (quot, num, den)
38 mp_size_t nsize = num->_mp_size;
39 mp_size_t dsize = den->_mp_size;
40 mp_size_t qsize, rsize;
41 mp_size_t sign_quotient = nsize ^ dsize;
42 unsigned normalization_steps;
49 /* Ensure space is enough for quotient. */
51 qsize = nsize - dsize + 1; /* qsize cannot be bigger than this. */
58 if (quot->_mp_alloc < qsize)
59 _mpz_realloc (quot, qsize);
65 /* Optimize division by a single-limb divisor. */
68 mpn_divmod_1 (qp, np, nsize, dp[0]);
69 qsize -= qp[qsize - 1] == 0;
70 quot->_mp_size = sign_quotient >= 0 ? qsize : -qsize;
76 rp = (mp_ptr) TMP_ALLOC ((nsize + 1) * BYTES_PER_MP_LIMB);
78 count_leading_zeros (normalization_steps, dp[dsize - 1]);
80 /* Normalize the denominator, i.e. make its most significant bit set by
81 shifting it NORMALIZATION_STEPS bits to the left. Also shift the
82 numerator the same number of steps (to keep the quotient the same!). */
83 if (normalization_steps != 0)
88 /* Shift up the denominator setting the most significant bit of
89 the most significant word. Use temporary storage not to clobber
90 the original contents of the denominator. */
91 tp = (mp_ptr) TMP_ALLOC (dsize * BYTES_PER_MP_LIMB);
92 mpn_lshift (tp, dp, dsize, normalization_steps);
95 /* Shift up the numerator, possibly introducing a new most
96 significant word. Move the shifted numerator in the remainder
98 nlimb = mpn_lshift (rp, np, nsize, normalization_steps);
109 /* The denominator is already normalized, as required. Copy it to
110 temporary space if it overlaps with the quotient. */
113 dp = (mp_ptr) TMP_ALLOC (dsize * BYTES_PER_MP_LIMB);
114 MPN_COPY ((mp_ptr) dp, qp, dsize);
117 /* Move the numerator to the remainder. */
118 MPN_COPY (rp, np, nsize);
122 q_limb = mpn_divmod (qp, rp, rsize, dp, dsize);
124 qsize = rsize - dsize;
131 quot->_mp_size = sign_quotient >= 0 ? qsize : -qsize;