xref: /netbsd-src/common/lib/libc/quad/qdivrem.c (revision 567219e1d7461bff1b180e494a9674a287b057a7)
1 /*	$NetBSD: qdivrem.c,v 1.4 2012/03/20 16:21:41 matt Exp $	*/
2 
3 /*-
4  * Copyright (c) 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This software was developed by the Computer Systems Engineering group
8  * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
9  * contributed to Berkeley.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #if defined(LIBC_SCCS) && !defined(lint)
38 #if 0
39 static char sccsid[] = "@(#)qdivrem.c	8.1 (Berkeley) 6/4/93";
40 #else
41 __RCSID("$NetBSD: qdivrem.c,v 1.4 2012/03/20 16:21:41 matt Exp $");
42 #endif
43 #endif /* LIBC_SCCS and not lint */
44 
45 /*
46  * Multiprecision divide.  This algorithm is from Knuth vol. 2 (2nd ed),
47  * section 4.3.1, pp. 257--259.
48  */
49 
50 #include "quad.h"
51 
52 #define	B	((int)1 << (unsigned int)HALF_BITS)	/* digit base */
53 
54 /* Combine two `digits' to make a single two-digit number. */
55 #define	COMBINE(a, b) (((u_int)(a) << (unsigned int)HALF_BITS) | (b))
56 
57 /* select a type for digits in base B: use unsigned short if they fit */
58 #if UINT_MAX == 0xffffffffU && USHRT_MAX >= 0xffff
59 typedef unsigned short digit;
60 #else
61 typedef u_int digit;
62 #endif
63 
64 static void shl(digit *p, int len, int sh);
65 
66 /*
67  * __qdivrem(u, v, rem) returns u/v and, optionally, sets *rem to u%v.
68  *
69  * We do this in base 2-sup-HALF_BITS, so that all intermediate products
70  * fit within u_int.  As a consequence, the maximum length dividend and
71  * divisor are 4 `digits' in this base (they are shorter if they have
72  * leading zeros).
73  */
74 u_quad_t
__qdivrem(u_quad_t uq,u_quad_t vq,u_quad_t * arq)75 __qdivrem(u_quad_t uq, u_quad_t vq, u_quad_t *arq)
76 {
77 	union uu tmp;
78 	digit *u, *v, *q;
79 	digit v1, v2;
80 	u_int qhat, rhat, t;
81 	int m, n, d, j, i;
82 	digit uspace[5], vspace[5], qspace[5];
83 
84 	/*
85 	 * Take care of special cases: divide by zero, and u < v.
86 	 */
87 	if (vq == 0) {
88 		/* divide by zero. */
89 		static volatile const unsigned int zero = 0;
90 
91 		tmp.ul[H] = tmp.ul[L] = 1 / zero;
92 		if (arq)
93 			*arq = uq;
94 		return (tmp.q);
95 	}
96 	if (uq < vq) {
97 		if (arq)
98 			*arq = uq;
99 		return (0);
100 	}
101 	u = &uspace[0];
102 	v = &vspace[0];
103 	q = &qspace[0];
104 
105 	/*
106 	 * Break dividend and divisor into digits in base B, then
107 	 * count leading zeros to determine m and n.  When done, we
108 	 * will have:
109 	 *	u = (u[1]u[2]...u[m+n]) sub B
110 	 *	v = (v[1]v[2]...v[n]) sub B
111 	 *	v[1] != 0
112 	 *	1 < n <= 4 (if n = 1, we use a different division algorithm)
113 	 *	m >= 0 (otherwise u < v, which we already checked)
114 	 *	m + n = 4
115 	 * and thus
116 	 *	m = 4 - n <= 2
117 	 */
118 	tmp.uq = uq;
119 	u[0] = 0;
120 	u[1] = (digit)HHALF(tmp.ul[H]);
121 	u[2] = (digit)LHALF(tmp.ul[H]);
122 	u[3] = (digit)HHALF(tmp.ul[L]);
123 	u[4] = (digit)LHALF(tmp.ul[L]);
124 	tmp.uq = vq;
125 	v[1] = (digit)HHALF(tmp.ul[H]);
126 	v[2] = (digit)LHALF(tmp.ul[H]);
127 	v[3] = (digit)HHALF(tmp.ul[L]);
128 	v[4] = (digit)LHALF(tmp.ul[L]);
129 	for (n = 4; v[1] == 0; v++) {
130 		if (--n == 1) {
131 			u_int rbj;	/* r*B+u[j] (not root boy jim) */
132 			digit q1, q2, q3, q4;
133 
134 			/*
135 			 * Change of plan, per exercise 16.
136 			 *	r = 0;
137 			 *	for j = 1..4:
138 			 *		q[j] = floor((r*B + u[j]) / v),
139 			 *		r = (r*B + u[j]) % v;
140 			 * We unroll this completely here.
141 			 */
142 			t = v[2];	/* nonzero, by definition */
143 			q1 = (digit)(u[1] / t);
144 			rbj = COMBINE(u[1] % t, u[2]);
145 			q2 = (digit)(rbj / t);
146 			rbj = COMBINE(rbj % t, u[3]);
147 			q3 = (digit)(rbj / t);
148 			rbj = COMBINE(rbj % t, u[4]);
149 			q4 = (digit)(rbj / t);
150 			if (arq)
151 				*arq = rbj % t;
152 			tmp.ul[H] = COMBINE(q1, q2);
153 			tmp.ul[L] = COMBINE(q3, q4);
154 			return (tmp.q);
155 		}
156 	}
157 
158 	/*
159 	 * By adjusting q once we determine m, we can guarantee that
160 	 * there is a complete four-digit quotient at &qspace[1] when
161 	 * we finally stop.
162 	 */
163 	for (m = 4 - n; u[1] == 0; u++)
164 		m--;
165 	for (i = 4 - m; --i >= 0;)
166 		q[i] = 0;
167 	q += 4 - m;
168 
169 	/*
170 	 * Here we run Program D, translated from MIX to C and acquiring
171 	 * a few minor changes.
172 	 *
173 	 * D1: choose multiplier 1 << d to ensure v[1] >= B/2.
174 	 */
175 	d = 0;
176 	for (t = v[1]; t < B / 2; t <<= (unsigned int)1)
177 		d++;
178 	if (d > 0) {
179 		shl(&u[0], m + n, d);		/* u <<= d */
180 		shl(&v[1], n - 1, d);		/* v <<= d */
181 	}
182 	/*
183 	 * D2: j = 0.
184 	 */
185 	j = 0;
186 	v1 = v[1];	/* for D3 -- note that v[1..n] are constant */
187 	v2 = v[2];	/* for D3 */
188 	do {
189 		digit uj0, uj1, uj2;
190 
191 		/*
192 		 * D3: Calculate qhat (\^q, in TeX notation).
193 		 * Let qhat = min((u[j]*B + u[j+1])/v[1], B-1), and
194 		 * let rhat = (u[j]*B + u[j+1]) mod v[1].
195 		 * While rhat < B and v[2]*qhat > rhat*B+u[j+2],
196 		 * decrement qhat and increase rhat correspondingly.
197 		 * Note that if rhat >= B, v[2]*qhat < rhat*B.
198 		 */
199 		uj0 = u[j + 0];	/* for D3 only -- note that u[j+...] change */
200 		uj1 = u[j + 1];	/* for D3 only */
201 		uj2 = u[j + 2];	/* for D3 only */
202 		if (uj0 == v1) {
203 			qhat = B;
204 			rhat = uj1;
205 			goto qhat_too_big;
206 		} else {
207 			u_int nn = COMBINE(uj0, uj1);
208 			qhat = nn / v1;
209 			rhat = nn % v1;
210 		}
211 		while (v2 * qhat > COMBINE(rhat, uj2)) {
212 	qhat_too_big:
213 			qhat--;
214 			if ((rhat += v1) >= B)
215 				break;
216 		}
217 		/*
218 		 * D4: Multiply and subtract.
219 		 * The variable `t' holds any borrows across the loop.
220 		 * We split this up so that we do not require v[0] = 0,
221 		 * and to eliminate a final special case.
222 		 */
223 		for (t = 0, i = n; i > 0; i--) {
224 			t = u[i + j] - v[i] * qhat - t;
225 			u[i + j] = (digit)LHALF(t);
226 			t = (B - HHALF(t)) & (B - 1);
227 		}
228 		t = u[j] - t;
229 		u[j] = (digit)LHALF(t);
230 		/*
231 		 * D5: test remainder.
232 		 * There is a borrow if and only if HHALF(t) is nonzero;
233 		 * in that (rare) case, qhat was too large (by exactly 1).
234 		 * Fix it by adding v[1..n] to u[j..j+n].
235 		 */
236 		if (HHALF(t)) {
237 			qhat--;
238 			for (t = 0, i = n; i > 0; i--) { /* D6: add back. */
239 				t += u[i + j] + v[i];
240 				u[i + j] = (digit)LHALF(t);
241 				t = HHALF(t);
242 			}
243 			u[j] = (digit)LHALF(u[j] + t);
244 		}
245 		q[j] = (digit)qhat;
246 	} while (++j <= m);		/* D7: loop on j. */
247 
248 	/*
249 	 * If caller wants the remainder, we have to calculate it as
250 	 * u[m..m+n] >> d (this is at most n digits and thus fits in
251 	 * u[m+1..m+n], but we may need more source digits).
252 	 */
253 	if (arq) {
254 		if (d) {
255 			for (i = m + n; i > m; --i)
256 				u[i] = (digit)(((u_int)u[i] >> d) |
257 				    LHALF((u_int)u[i - 1] << (unsigned int)(HALF_BITS - d)));
258 			u[i] = 0;
259 		}
260 		tmp.ul[H] = COMBINE(uspace[1], uspace[2]);
261 		tmp.ul[L] = COMBINE(uspace[3], uspace[4]);
262 		*arq = tmp.q;
263 	}
264 
265 	tmp.ul[H] = COMBINE(qspace[1], qspace[2]);
266 	tmp.ul[L] = COMBINE(qspace[3], qspace[4]);
267 	return (tmp.q);
268 }
269 
270 /*
271  * Shift p[0]..p[len] left `sh' bits, ignoring any bits that
272  * `fall out' the left (there never will be any such anyway).
273  * We may assume len >= 0.  NOTE THAT THIS WRITES len+1 DIGITS.
274  */
275 static void
shl(digit * p,int len,int sh)276 shl(digit *p, int len, int sh)
277 {
278 	int i;
279 
280 	for (i = 0; i < len; i++)
281 		p[i] = (digit)(LHALF((u_int)p[i] << sh) |
282 		    ((u_int)p[i + 1] >> (HALF_BITS - sh)));
283 	p[i] = (digit)(LHALF((u_int)p[i] << sh));
284 }
285