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 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 3 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. If not, see http://www.gnu.org/licenses/. */
34 mpn_udiv_w_sdiv (rp, a1, a0, d)
35 mp_limb_t *rp, a1, a0, d;
43 if ((mp_limb_signed_t) d >= 0)
45 if (a1 < d - a1 - (a0 >> (GMP_LIMB_BITS - 1)))
47 /* dividend, divisor, and quotient are nonnegative */
48 sdiv_qrnnd (q, r, a1, a0, d);
52 /* Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d */
53 sub_ddmmss (c1, c0, a1, a0, d >> 1, d << (GMP_LIMB_BITS - 1));
54 /* Divide (c1*2^32 + c0) by d */
55 sdiv_qrnnd (q, r, c1, c0, d);
56 /* Add 2^31 to quotient */
57 q += (mp_limb_t) 1 << (GMP_LIMB_BITS - 1);
62 b1 = d >> 1; /* d/2, between 2^30 and 2^31 - 1 */
63 c1 = a1 >> 1; /* A/2 */
64 c0 = (a1 << (GMP_LIMB_BITS - 1)) + (a0 >> 1);
66 if (a1 < b1) /* A < 2^32*b1, so A/2 < 2^31*b1 */
68 sdiv_qrnnd (q, r, c1, c0, b1); /* (A/2) / (d/2) */
70 r = 2*r + (a0 & 1); /* Remainder from A/(2*b1) */
87 else if (c1 < b1) /* So 2^31 <= (A/2)/b1 < 2^32 */
90 c0 = ~c0; /* logical NOT */
92 sdiv_qrnnd (q, r, c1, c0, b1); /* (A/2) / (d/2) */
94 q = ~q; /* (A/2)/b1 */
97 r = 2*r + (a0 & 1); /* A/(2*b1) */
115 else /* Implies c1 = b1 */
116 { /* Hence a1 = d - 1 = 2*b1 - 1 */