/* mpn_bdiv_q -- Hensel division with precomputed inverse, returning quotient.
Contributed to the GNU project by Torbjorn Granlund.
THE FUNCTIONS IN THIS FILE ARE INTERNAL WITH MUTABLE INTERFACES. IT IS ONLY
SAFE TO REACH THEM THROUGH DOCUMENTED INTERFACES. IN FACT, IT IS ALMOST
GUARANTEED THAT THEY WILL CHANGE OR DISAPPEAR IN A FUTURE GMP RELEASE.
Copyright 2006, 2007, 2009 Free Software Foundation, Inc.
This file is part of the GNU MP Library.
The GNU MP Library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any
later version.
or both in parallel, as here.
The GNU MP Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the GNU MP Library. If not,
see https://www.gnu.org/licenses/. */
#include "gmp.h"
#include "gmp-impl.h"
#include "longlong.h"
/* Computes Q = N / D mod B^n. */
void
mpn_bdiv_q_2 (mp_ptr qp,
mp_srcptr np, mp_size_t nn,
mp_srcptr dp)
{
mp_limb_t d0, d1;
mp_limb_t dinv;
mp_limb_t bic;
mp_size_t i;
mp_limb_t q;
mp_limb_t ypl, xpl;
mp_limb_t hpl, lpl, rl;
mp_limb_t nx, ny;
mp_limb_t zl;
ASSERT (nn >= 2);
ASSERT ((dp[0] & 1) != 0);
/* FIXME: Add ASSERTs for allowable overlapping; i.e., that qp = np is OK,
but some over N/Q overlaps will not work. */
d0 = dp[0];
d1 = dp[1];
bic = 0;
nx = np[0];
ny = np[1];
binvert_limb (dinv, d0);
for (i = nn - 2; i > 0; i--)
{
mp_limb_t cl;
mp_limb_t al;
mp_limb_t nz;
q = dinv * nx;
qp[0] = q;
umul_ppmm (ypl, xpl, d0, q);
ASSERT(xpl == nx);
umul_ppmm (hpl, lpl, d1, q);
lpl += ypl;
cl = (lpl < ypl) + hpl;
rl = ny;
zl = rl - lpl;
cl += zl > rl;
ny = zl;
nz = np[2];
rl = nz;
zl = rl - cl;
cl = zl > rl;
al = zl - bic;
cl += al > zl;
nz = al;
bic = cl;
qp++;
np++;
nx = ny;
ny = nz;
}
q = dinv * nx;
qp[0] = q;
umul_ppmm (ypl, xpl, d0, q);
ASSERT(xpl == nx);
lpl = d1 * q;
lpl += ypl;
rl = ny;
zl = rl - lpl;
ny = zl;
/* Final limb */
q = dinv * ny;
qp[1] = q;
}