1 /* mpn_udiv_w_sdiv -- implement udiv_qrnnd on machines with only signed
4 Contributed by Peter L. Montgomery.
6 THIS IS AN INTERNAL FUNCTION WITH A MUTABLE INTERFACE. IT IS ONLY SAFE
7 TO REACH THIS FUNCTION THROUGH DOCUMENTED INTERFACES. IN FACT, IT IS
8 ALMOST GUARANTEED THAT THIS FUNCTION WILL CHANGE OR DISAPPEAR IN A FUTURE
12 Copyright (C) 1992, 1994, 1996, 2000 Free Software Foundation, Inc.
14 This file is part of the GNU MP Library.
16 The GNU MP Library is free software; you can redistribute it and/or modify
17 it under the terms of the GNU Lesser General Public License as published by
18 the Free Software Foundation; either version 2.1 of the License, or (at your
19 option) any later version.
21 The GNU MP Library is distributed in the hope that it will be useful, but
22 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
23 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
24 License for more details.
26 You should have received a copy of the GNU Lesser General Public License
27 along with the GNU MP Library; see the file COPYING.LIB. If not, write to
28 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
29 MA 02111-1307, USA. */
36 mpn_udiv_w_sdiv (rp, a1, a0, d)
37 mp_limb_t *rp, a1, a0, d;
42 if ((mp_limb_signed_t) d >= 0)
44 if (a1 < d - a1 - (a0 >> (BITS_PER_MP_LIMB - 1)))
46 /* dividend, divisor, and quotient are nonnegative */
47 sdiv_qrnnd (q, r, a1, a0, d);
51 /* Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d */
52 sub_ddmmss (c1, c0, a1, a0, d >> 1, d << (BITS_PER_MP_LIMB - 1));
53 /* Divide (c1*2^32 + c0) by d */
54 sdiv_qrnnd (q, r, c1, c0, d);
55 /* Add 2^31 to quotient */
56 q += (mp_limb_t) 1 << (BITS_PER_MP_LIMB - 1);
61 b1 = d >> 1; /* d/2, between 2^30 and 2^31 - 1 */
62 c1 = a1 >> 1; /* A/2 */
63 c0 = (a1 << (BITS_PER_MP_LIMB - 1)) + (a0 >> 1);
65 if (a1 < b1) /* A < 2^32*b1, so A/2 < 2^31*b1 */
67 sdiv_qrnnd (q, r, c1, c0, b1); /* (A/2) / (d/2) */
69 r = 2*r + (a0 & 1); /* Remainder from A/(2*b1) */
86 else if (c1 < b1) /* So 2^31 <= (A/2)/b1 < 2^32 */
89 c0 = ~c0; /* logical NOT */
91 sdiv_qrnnd (q, r, c1, c0, b1); /* (A/2) / (d/2) */
93 q = ~q; /* (A/2)/b1 */
96 r = 2*r + (a0 & 1); /* A/(2*b1) */
114 else /* Implies c1 = b1 */
115 { /* Hence a1 = d - 1 = 2*b1 - 1 */