beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpn / generic / divrem.c
blobf420992746e818fe28c359a90d99c5ee05002668
1 /* mpn_divrem -- Divide natural numbers, producing both remainder and
2 quotient. This is now just a middle layer calling mpn_tdiv_qr.
4 Copyright 1993-1997, 1999-2002, 2005 Free Software Foundation, Inc.
6 This file is part of the GNU MP Library.
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of either:
11 * the GNU Lesser General Public License as published by the Free
12 Software Foundation; either version 3 of the License, or (at your
13 option) any later version.
17 * the GNU General Public License as published by the Free Software
18 Foundation; either version 2 of the License, or (at your option) any
19 later version.
21 or both in parallel, as here.
23 The GNU MP Library is distributed in the hope that it will be useful, but
24 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
25 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
26 for more details.
28 You should have received copies of the GNU General Public License and the
29 GNU Lesser General Public License along with the GNU MP Library. If not,
30 see https://www.gnu.org/licenses/. */
32 #include "gmp.h"
33 #include "gmp-impl.h"
34 #include "longlong.h"
36 mp_limb_t
37 mpn_divrem (mp_ptr qp, mp_size_t qxn,
38 mp_ptr np, mp_size_t nn,
39 mp_srcptr dp, mp_size_t dn)
41 ASSERT (qxn >= 0);
42 ASSERT (nn >= dn);
43 ASSERT (dn >= 1);
44 ASSERT (dp[dn-1] & GMP_NUMB_HIGHBIT);
45 ASSERT (! MPN_OVERLAP_P (np, nn, dp, dn));
46 ASSERT (! MPN_OVERLAP_P (qp, nn-dn+qxn, np, nn) || qp==np+dn+qxn);
47 ASSERT (! MPN_OVERLAP_P (qp, nn-dn+qxn, dp, dn));
48 ASSERT_MPN (np, nn);
49 ASSERT_MPN (dp, dn);
51 if (dn == 1)
53 mp_limb_t ret;
54 mp_ptr q2p;
55 mp_size_t qn;
56 TMP_DECL;
58 TMP_MARK;
59 q2p = TMP_ALLOC_LIMBS (nn + qxn);
61 np[0] = mpn_divrem_1 (q2p, qxn, np, nn, dp[0]);
62 qn = nn + qxn - 1;
63 MPN_COPY (qp, q2p, qn);
64 ret = q2p[qn];
66 TMP_FREE;
67 return ret;
69 else if (dn == 2)
71 return mpn_divrem_2 (qp, qxn, np, nn, dp);
73 else
75 mp_ptr rp, q2p;
76 mp_limb_t qhl;
77 mp_size_t qn;
78 TMP_DECL;
80 TMP_MARK;
81 if (UNLIKELY (qxn != 0))
83 mp_ptr n2p;
84 n2p = TMP_ALLOC_LIMBS (nn + qxn);
85 MPN_ZERO (n2p, qxn);
86 MPN_COPY (n2p + qxn, np, nn);
87 q2p = TMP_ALLOC_LIMBS (nn - dn + qxn + 1);
88 rp = TMP_ALLOC_LIMBS (dn);
89 mpn_tdiv_qr (q2p, rp, 0L, n2p, nn + qxn, dp, dn);
90 MPN_COPY (np, rp, dn);
91 qn = nn - dn + qxn;
92 MPN_COPY (qp, q2p, qn);
93 qhl = q2p[qn];
95 else
97 q2p = TMP_ALLOC_LIMBS (nn - dn + 1);
98 rp = TMP_ALLOC_LIMBS (dn);
99 mpn_tdiv_qr (q2p, rp, 0L, np, nn, dp, dn);
100 MPN_COPY (np, rp, dn); /* overwrite np area with remainder */
101 qn = nn - dn;
102 MPN_COPY (qp, q2p, qn);
103 qhl = q2p[qn];
105 TMP_FREE;
106 return qhl;