home *** CD-ROM | disk | FTP | other *** search
- /* div - divide unsigned ints by shifting and subtracting */
- /* 1982/10/17 16:20
- submitted by William G. Hutchison, Jr.
- P.O. Box 278
- Exton, PA 19341-0278
- U.S.A.
-
- CompuServe 70665,1307
-
- */
-
- #ifdef UNIX
- unsigned
- #endif
- div(x, y, qq, rr)
- unsigned x /* input: dividend */;
- unsigned y /* input: divisor */;
- unsigned *qq /* output: quotient */;
- unsigned *rr /* output: remainder */;
- {
- unsigned q, r, w;
- if (y == 0) error("divide by zero.");
- q= 0;
- r= x;
- w= y;
- while (w <= r) w<<=1;
- while (w != y) {
- q<<= 1;
- w>>= 1;
- if (w <= r) {
- r-= w;
- q++;
- }
- }
- /* (x == q * y + r) && (0 <= r) && (r < y) */
- *rr= r;
- return (*qq= q);
- } /* end div */
-
- /* Alagic, Suad & Arbib, Michael A. "The Design of Well Structured
- and Correct Programs" Springer-Verlag, New York 1978, p. 44. */
-
- #ifdef MAINLY
- #else
- #include "c80def.h"
- #include "printf.c"
-
- main(){
- unsigned a, b, e, q, r;
- static unsigned tests= 1000;
- static unsigned thou= 0;
- printf("Starting test of div\n");
- for(e= a= 0; a < 32767; a++){
- for(b= 32767/(a+1); b > 0; b--)
- {
- if (a != b * div(a,b,&q,&r) + r || r >= b)
- printf("error #%d: %d <> %d * %d + %d\n",
- e, a, b, q, r);
- if (--tests == 0) {
- printf("%5d000 tests finished.\n", ++thou);
- tests= 1000;
- }
- }
- }
- printf("Testing found %d errors.\n", e);
- } /* end main */
-
- error(s) char *s;
- {
- printf("%s\n", s);
- } /* end error */
- #endif