mpdigdiv.c 732 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #include "os.h"
  2. #include <mp.h>
  3. #include "dat.h"
  4. //
  5. // divide two digits by one and return quotient
  6. //
  7. void
  8. mpdigdiv(mpdigit *dividend, mpdigit divisor, mpdigit *quotient)
  9. {
  10. mpdigit hi, lo, q, x, y;
  11. int i;
  12. hi = dividend[1];
  13. lo = dividend[0];
  14. // return highest digit value if the result >= 2**32
  15. if(hi >= divisor || divisor == 0){
  16. divisor = 0;
  17. *quotient = ~divisor;
  18. return;
  19. }
  20. // at this point we know that hi < divisor
  21. // just shift and subtract till we're done
  22. q = 0;
  23. x = divisor;
  24. for(i = Dbits-1; hi > 0 && i >= 0; i--){
  25. x >>= 1;
  26. if(x > hi)
  27. continue;
  28. y = divisor<<i;
  29. if(x == hi && y > lo)
  30. continue;
  31. if(y > lo)
  32. hi--;
  33. lo -= y;
  34. hi -= x;
  35. q |= 1<<i;
  36. }
  37. q += lo/divisor;
  38. *quotient = q;
  39. }