home *** CD-ROM | disk | FTP | other *** search
/ Programmer 7500 / MAX_PROGRAMMERS.iso / INFO / C / C80TCOG.ZIP / DIV.C < prev    next >
Encoding:
C/C++ Source or Header  |  1988-08-08  |  2.0 KB  |  73 lines

  1. /* div - divide unsigned ints by shifting and subtracting       */
  2. /*                                                      1982/10/17 16:20
  3.         submitted by    William G. Hutchison, Jr.
  4.                         P.O. Box 278
  5.                         Exton, PA 19341-0278
  6.                         U.S.A.
  7.  
  8.                         CompuServe 70665,1307
  9.  
  10.  */
  11.  
  12. #ifdef UNIX
  13. unsigned
  14. #endif
  15. div(x, y, qq, rr)
  16. unsigned x /* input: dividend */;
  17. unsigned y /* input: divisor */;
  18. unsigned *qq /* output: quotient */;
  19. unsigned *rr /* output: remainder */; 
  20. {
  21.         unsigned q, r, w; 
  22.         if (y == 0) error("divide by zero.");
  23.         q= 0; 
  24.         r= x; 
  25.         w= y; 
  26.         while (w <= r) w<<=1;
  27.         while (w != y) { 
  28.                 q<<= 1; 
  29.                 w>>= 1;
  30.                 if (w <= r) { 
  31.                         r-= w; 
  32.                         q++;
  33.                 }
  34.         }
  35.         /* (x == q * y + r) && (0 <= r) && (r < y) */
  36.         *rr= r; 
  37.         return  (*qq= q); 
  38. } /* end div */
  39.  
  40. /* Alagic, Suad & Arbib, Michael A. "The Design of Well Structured
  41. and Correct Programs" Springer-Verlag, New York 1978, p. 44.   */
  42.  
  43. #ifdef MAINLY
  44. #else
  45. #include "c80def.h"
  46. #include "printf.c"
  47.  
  48. main(){
  49.         unsigned a, b, e, q, r;
  50.         static unsigned tests= 1000;
  51.         static unsigned thou= 0;
  52.         printf("Starting test of div\n");
  53.         for(e= a= 0; a < 32767; a++){
  54.                 for(b= 32767/(a+1); b > 0; b--)
  55.                 {
  56.                         if (a != b * div(a,b,&q,&r) + r || r >= b)
  57.                               printf("error #%d: %d <> %d * %d + %d\n",
  58.                 e, a, b, q, r);
  59.                         if (--tests == 0) {
  60.                             printf("%5d000 tests finished.\n", ++thou);
  61.                                 tests= 1000;
  62.                         }
  63.                 }
  64.         }
  65.         printf("Testing found %d errors.\n", e);
  66. } /* end main */
  67.  
  68. error(s) char *s; 
  69. {
  70.         printf("%s\n", s);
  71. } /* end error */
  72. #endif
  73.