1 /* mpn_dc_div_q -- divide-and-conquer division, returning exact quotient
2    only.
3 
4    Contributed to the GNU project by Torbjorn Granlund and Marco Bodrato.
5 
6    THE FUNCTION IN THIS FILE IS INTERNAL WITH A MUTABLE INTERFACE.  IT IS ONLY
7    SAFE TO REACH IT THROUGH DOCUMENTED INTERFACES.  IN FACT, IT IS ALMOST
8    GUARANTEED THAT IT WILL CHANGE OR DISAPPEAR IN A FUTURE GMP RELEASE.
9 
10 Copyright 2006, 2007, 2009, 2010 Free Software Foundation, Inc.
11 
12 This file is part of the GNU MP Library.
13 
14 The GNU MP Library is free software; you can redistribute it and/or modify
15 it under the terms of either:
16 
17   * the GNU Lesser General Public License as published by the Free
18     Software Foundation; either version 3 of the License, or (at your
19     option) any later version.
20 
21 or
22 
23   * the GNU General Public License as published by the Free Software
24     Foundation; either version 2 of the License, or (at your option) any
25     later version.
26 
27 or both in parallel, as here.
28 
29 The GNU MP Library is distributed in the hope that it will be useful, but
30 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
31 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
32 for more details.
33 
34 You should have received copies of the GNU General Public License and the
35 GNU Lesser General Public License along with the GNU MP Library.  If not,
36 see https://www.gnu.org/licenses/.  */
37 
38 #include "gmp-impl.h"
39 
40 
41 mp_limb_t
mpn_dcpi1_div_q(mp_ptr qp,mp_ptr np,mp_size_t nn,mp_srcptr dp,mp_size_t dn,gmp_pi1_t * dinv)42 mpn_dcpi1_div_q (mp_ptr qp, mp_ptr np, mp_size_t nn,
43 		 mp_srcptr dp, mp_size_t dn, gmp_pi1_t *dinv)
44 {
45   mp_ptr tp, wp;
46   mp_limb_t qh;
47   mp_size_t qn;
48   TMP_DECL;
49 
50   TMP_MARK;
51 
52   ASSERT (dn >= 6);
53   ASSERT (nn - dn >= 3);
54   ASSERT (dp[dn-1] & GMP_NUMB_HIGHBIT);
55 
56   tp = TMP_ALLOC_LIMBS (nn + 1);
57   MPN_COPY (tp + 1, np, nn);
58   tp[0] = 0;
59 
60   qn = nn - dn;
61   wp = TMP_ALLOC_LIMBS (qn + 1);
62 
63   qh = mpn_dcpi1_divappr_q (wp, tp, nn + 1, dp, dn, dinv);
64 
65   if (wp[0] == 0)
66     {
67       mp_limb_t cy;
68 
69       if (qn > dn)
70 	mpn_mul (tp, wp + 1, qn, dp, dn);
71       else
72 	mpn_mul (tp, dp, dn, wp + 1, qn);
73 
74       cy = (qh != 0) ? mpn_add_n (tp + qn, tp + qn, dp, dn) : 0;
75 
76       if (cy || mpn_cmp (tp, np, nn) > 0) /* At most is wrong by one, no cycle. */
77 	qh -= mpn_sub_1 (qp, wp + 1, qn, 1);
78       else /* Same as below */
79 	MPN_COPY (qp, wp + 1, qn);
80     }
81   else
82     MPN_COPY (qp, wp + 1, qn);
83 
84   TMP_FREE;
85   return qh;
86 }
87