fork(18) download
  1. #include <stdio.h>
  2. #include <limits.h>
  3.  
  4. #define INT_BITS (sizeof(int)*8)
  5.  
  6. typedef struct div_result div_result;
  7. struct div_result {
  8. int quotient;
  9. int remainder;
  10. };
  11.  
  12. div_result divide(int dividend, int divisor) {
  13. div_result result;
  14.  
  15. if (divisor == 0) {
  16. result.quotient = dividend < 0 ? INT_MIN : INT_MAX;
  17. result.remainder = 0;
  18. return result;
  19. }
  20.  
  21. if ((dividend == INT_MIN) && (divisor == -1)) {
  22. result.quotient = INT_MAX;
  23. result.remainder = 0;
  24. return result;
  25. }
  26.  
  27. int negative = (dividend < 0) ^ (divisor < 0);
  28.  
  29. if (dividend < 0) {
  30. dividend = -dividend;
  31. }
  32. if (divisor < 0) {
  33. divisor = -divisor;
  34. }
  35.  
  36. int quotient = 0, remainder = 0;
  37.  
  38. for (int i = 0; i < sizeof(int)*8; i++) {
  39. quotient <<= 1;
  40.  
  41. remainder <<= 1;
  42. remainder += (dividend >> (INT_BITS - 1)) & 1;
  43. dividend <<= 1;
  44.  
  45. if (remainder >= divisor) {
  46. remainder -= divisor;
  47. quotient++;
  48. }
  49. }
  50.  
  51. if (negative) {
  52. result.quotient = -quotient;
  53. result.remainder = -remainder;
  54. } else {
  55. result.quotient = quotient;
  56. result.remainder = remainder;
  57. }
  58. return result;
  59. }
  60.  
  61. int main() {
  62. int dividend, divisor;
  63. scanf("%i%i", &dividend, &divisor);
  64.  
  65. div_result result = divide(dividend, divisor);
  66. printf("%i %i\r\n", result.quotient, result.remainder);
  67. }
  68.  
Success #stdin #stdout 0s 2252KB
stdin
1
0
stdout
2147483647 0