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 the GNU Lesser General Public License as published by
16 the Free Software Foundation; either version 3 of the License, or (at your
17 option) any later version.
18 
19 The GNU MP Library is distributed in the hope that it will be useful, but
20 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
21 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
22 License for more details.
23 
24 You should have received a copy of the GNU Lesser General Public License
25 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
26 
27 #include "gmp.h"
28 #include "gmp-impl.h"
29 
30 
31 mp_limb_t
32 mpn_dcpi1_div_q (mp_ptr qp, mp_ptr np, mp_size_t nn,
33 		 mp_srcptr dp, mp_size_t dn, gmp_pi1_t *dinv)
34 {
35   mp_ptr tp, wp;
36   mp_limb_t qh;
37   mp_size_t qn;
38   TMP_DECL;
39 
40   TMP_MARK;
41 
42   ASSERT (dn >= 6);
43   ASSERT (nn - dn >= 3);
44   ASSERT (dp[dn-1] & GMP_NUMB_HIGHBIT);
45 
46   tp = TMP_SALLOC_LIMBS (nn + 1);
47   MPN_COPY (tp + 1, np, nn);
48   tp[0] = 0;
49 
50   qn = nn - dn;
51   wp = TMP_SALLOC_LIMBS (qn + 1);
52 
53   qh = mpn_dcpi1_divappr_q (wp, tp, nn + 1, dp, dn, dinv);
54 
55   if (wp[0] == 0)
56     {
57       mp_limb_t cy;
58 
59       if (qn > dn)
60 	mpn_mul (tp, wp + 1, qn, dp, dn);
61       else
62 	mpn_mul (tp, dp, dn, wp + 1, qn);
63 
64       cy = (qh != 0) ? mpn_add_n (tp + qn, tp + qn, dp, dn) : 0;
65 
66       if (cy || mpn_cmp (tp, np, nn) > 0) /* At most is wrong by one, no cycle. */
67 	qh -= mpn_sub_1 (qp, wp + 1, qn, 1);
68       else /* Same as below */
69 	MPN_COPY (qp, wp + 1, qn);
70     }
71   else
72     MPN_COPY (qp, wp + 1, qn);
73 
74   TMP_FREE;
75   return qh;
76 }
77