beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpz / tdiv_qr.c
blobab9a37dae9c47b19640488aa844bbffccac97755
1 /* mpz_tdiv_qr(quot,rem,dividend,divisor) -- Set QUOT to DIVIDEND/DIVISOR,
2 and REM to DIVIDEND mod DIVISOR.
4 Copyright 1991, 1993, 1994, 2000, 2001, 2005, 2011, 2012 Free Software
5 Foundation, Inc.
7 This file is part of the GNU MP Library.
9 The GNU MP Library is free software; you can redistribute it and/or modify
10 it under the terms of either:
12 * the GNU Lesser General Public License as published by the Free
13 Software Foundation; either version 3 of the License, or (at your
14 option) any later version.
18 * the GNU General Public License as published by the Free Software
19 Foundation; either version 2 of the License, or (at your option) any
20 later version.
22 or both in parallel, as here.
24 The GNU MP Library is distributed in the hope that it will be useful, but
25 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
26 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
27 for more details.
29 You should have received copies of the GNU General Public License and the
30 GNU Lesser General Public License along with the GNU MP Library. If not,
31 see https://www.gnu.org/licenses/. */
33 #include "gmp.h"
34 #include "gmp-impl.h"
35 #include "longlong.h"
37 void
38 mpz_tdiv_qr (mpz_ptr quot, mpz_ptr rem, mpz_srcptr num, mpz_srcptr den)
40 mp_size_t ql;
41 mp_size_t ns, ds, nl, dl;
42 mp_ptr np, dp, qp, rp;
43 TMP_DECL;
45 ns = SIZ (num);
46 ds = SIZ (den);
47 nl = ABS (ns);
48 dl = ABS (ds);
49 ql = nl - dl + 1;
51 if (UNLIKELY (dl == 0))
52 DIVIDE_BY_ZERO;
54 rp = MPZ_REALLOC (rem, dl);
56 if (ql <= 0)
58 if (num != rem)
60 np = PTR (num);
61 MPN_COPY (rp, np, nl);
62 SIZ (rem) = SIZ (num);
64 /* This needs to follow the assignment to rem, in case the
65 numerator and quotient are the same. */
66 SIZ (quot) = 0;
67 return;
70 qp = MPZ_REALLOC (quot, ql);
72 TMP_MARK;
73 np = PTR (num);
74 dp = PTR (den);
76 /* FIXME: We should think about how to handle the temporary allocation.
77 Perhaps mpn_tdiv_qr should handle it, since it anyway often needs to
78 allocate temp space. */
80 /* Copy denominator to temporary space if it overlaps with the quotient
81 or remainder. */
82 if (dp == rp || dp == qp)
84 mp_ptr tp;
85 tp = TMP_ALLOC_LIMBS (dl);
86 MPN_COPY (tp, dp, dl);
87 dp = tp;
89 /* Copy numerator to temporary space if it overlaps with the quotient or
90 remainder. */
91 if (np == rp || np == qp)
93 mp_ptr tp;
94 tp = TMP_ALLOC_LIMBS (nl);
95 MPN_COPY (tp, np, nl);
96 np = tp;
99 mpn_tdiv_qr (qp, rp, 0L, np, nl, dp, dl);
101 ql -= qp[ql - 1] == 0;
102 MPN_NORMALIZE (rp, dl);
104 SIZ (quot) = (ns ^ ds) >= 0 ? ql : -ql;
105 SIZ (rem) = ns >= 0 ? dl : -dl;
106 TMP_FREE;