fork(2) download
  1. #include <stdio.h>
  2. #include <limits.h>
  3.  
  4. // define infinity as ULONG_MAX
  5. #define INF ULONG_MAX
  6.  
  7. double abs(double i) {
  8. return i >= 0 ? i : -i;
  9. }
  10.  
  11. // Function to perform division of two numbers using binary search algorithm
  12. double divide(double x, double y)
  13. {
  14. // handle divisibility by 0
  15. if (y == 0) {
  16. return INF; // return infinity
  17. }
  18.  
  19. // set range for result [low, high]. high is set to infinity
  20. // to handle the case when y < 1, x < result < INF
  21. double low = 0, high = INF;
  22.  
  23. // set accuracy of the result
  24. double precision = 0.001;
  25.  
  26. // store sign of the result
  27. int sign = 1;
  28. if (x * y < 0) {
  29. sign = -1;
  30. }
  31.  
  32. // make both input numbers positive
  33. x = abs(x);
  34. y = abs(y);
  35.  
  36. while (1)
  37. {
  38. // calculate mid
  39. double mid = low + ((high - low)/2);
  40.  
  41. // if y*mid is almost equal to x, return mid
  42. if (abs(y * mid - x) <= precision)
  43. return mid * sign;
  44.  
  45. // if y*mid is less than x, update low to mid
  46. if (y * mid < x)
  47. low = mid;
  48. else
  49. // if y*mid is more than x, update high to mid
  50. high = mid;
  51. }
  52. }
  53.  
  54. // Division of two numbers using binary search algorithm
  55. int main(void)
  56. {
  57. printf("%f", divide(22, 7));
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0s 4308KB
stdin
Standard input is empty
stdout
3.142822