1 /* mpn_udiv_w_sdiv -- implement udiv_qrnnd on machines with only signed
4 Contributed by Peter L. Montgomery.
6 Copyright (C) 1992, 1994, 1996 Free Software Foundation, Inc.
8 This file is part of the GNU MP Library.
10 The GNU MP Library is free software; you can redistribute it and/or modify
11 it under the terms of the GNU Library General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or (at your
13 option) any later version.
15 The GNU MP Library is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
18 License for more details.
20 You should have received a copy of the GNU Library General Public License
21 along with the GNU MP Library; see the file COPYING.LIB. If not, write to
22 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23 MA 02111-1307, USA. */
30 mpn_udiv_w_sdiv (rp, a1, a0, d)
31 mp_limb_t *rp, a1, a0, d;
36 if ((mp_limb_signed_t) d >= 0)
38 if (a1 < d - a1 - (a0 >> (BITS_PER_MP_LIMB - 1)))
40 /* dividend, divisor, and quotient are nonnegative */
41 sdiv_qrnnd (q, r, a1, a0, d);
45 /* Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d */
46 sub_ddmmss (c1, c0, a1, a0, d >> 1, d << (BITS_PER_MP_LIMB - 1));
47 /* Divide (c1*2^32 + c0) by d */
48 sdiv_qrnnd (q, r, c1, c0, d);
49 /* Add 2^31 to quotient */
50 q += (mp_limb_t) 1 << (BITS_PER_MP_LIMB - 1);
55 b1 = d >> 1; /* d/2, between 2^30 and 2^31 - 1 */
56 c1 = a1 >> 1; /* A/2 */
57 c0 = (a1 << (BITS_PER_MP_LIMB - 1)) + (a0 >> 1);
59 if (a1 < b1) /* A < 2^32*b1, so A/2 < 2^31*b1 */
61 sdiv_qrnnd (q, r, c1, c0, b1); /* (A/2) / (d/2) */
63 r = 2*r + (a0 & 1); /* Remainder from A/(2*b1) */
80 else if (c1 < b1) /* So 2^31 <= (A/2)/b1 < 2^32 */
83 c0 = ~c0; /* logical NOT */
85 sdiv_qrnnd (q, r, c1, c0, b1); /* (A/2) / (d/2) */
87 q = ~q; /* (A/2)/b1 */
90 r = 2*r + (a0 & 1); /* A/(2*b1) */
108 else /* Implies c1 = b1 */
109 { /* Hence a1 = d - 1 = 2*b1 - 1 */