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