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