fork download
  1. #include <iostream>
  2. #include <limits>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. double moda(double x, double y)
  8. {
  9. return x - (y * static_cast<int>(x / y));
  10. }
  11.  
  12. template <class S, class T>
  13. S unsafe_cast(T t)
  14. {
  15. union
  16. {
  17. T _t;
  18. S _s;
  19. } a;
  20. a._t = t;
  21. return a._s;
  22. }
  23.  
  24. double mod(double x, double y)
  25. {
  26. if ((unsafe_cast<unsigned long long>(x) | unsafe_cast<unsigned long long>(y)) & (0x1 << 63))
  27. {
  28. return moda(x, y);
  29. }
  30.  
  31. while (x - y >= 0)
  32. {
  33. x -= y;
  34. }
  35.  
  36. return x;
  37. }
  38.  
  39. void test_case(double x, double y)
  40. {
  41. cout << "case: " << x << " % " << y << "\n";
  42. cout << "actual: " << fmod(x, y) << "\n";
  43. cout << "moda: " << mod(x, y) << "\n";
  44. cout << " --- " << endl;
  45. }
  46.  
  47. int main() {
  48. test_case(5, 3);
  49. test_case(-5, 3);
  50. test_case(5, -3);
  51. test_case(-5, -3);
  52.  
  53. test_case(5, numeric_limits<double>::infinity());
  54. return 0;
  55. }
Time limit exceeded #stdin #stdout 5s 3412KB
stdin
Standard input is empty
stdout
case: 5 % 3
actual: 2
moda: 2
 --- 
case: -5 % 3
actual: -2
moda: -5
 ---