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