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