fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <string>
  4.  
  5. int lcm(int a, int b) {
  6. int na = 1, nb = 1;
  7. while (a * na != b * nb) {
  8. if (a * na < b * nb) ++na; else ++nb;
  9. }
  10. return a * na;
  11. }
  12.  
  13. int gcm(int a, int b) {
  14. int i = a < b ? a : b;
  15. for (; i > 1; --i) {
  16. if (a % i == 0 && b % i == 0) break;
  17. }
  18. return i;
  19. }
  20.  
  21. class Frac {
  22. private:
  23. int a, b;
  24.  
  25. public:
  26. Frac(int num) {
  27. a = num;
  28. b = 1;
  29. }
  30.  
  31. Frac(int num, int den) {
  32. a = num;
  33. b = den;
  34. }
  35.  
  36. Frac(const Frac &f) {
  37. *this = f;
  38. }
  39.  
  40. Frac &operator=(const Frac &f) {
  41. a = f.a;
  42. b = f.b;
  43. return *this;
  44. }
  45.  
  46. Frac &operator+=(const Frac &f) {
  47. Frac tmp = *this;
  48. b = lcm(tmp.b, f.b);
  49. a = tmp.a * b / tmp.b + f.a * b / f.b;
  50. return *this;
  51. }
  52.  
  53. Frac &operator*=(const Frac &f) {
  54. a *= f.a;
  55. b *= f.b;
  56. return *this;
  57. }
  58.  
  59. Frac reduce() const {
  60. Frac ret = *this;
  61. int g = gcm(a, b);
  62. ret.a /= g;
  63. ret.b /= g;
  64. return ret;
  65. }
  66.  
  67. std::string str() const {
  68. char buf[32];
  69. if (b == 1) {
  70. snprintf(buf, sizeof(buf), "%d", a);
  71. } else {
  72. snprintf(buf, sizeof(buf), "%d/%d", a, b);
  73. }
  74. return buf;
  75. }
  76. };
  77.  
  78. Frac operator+(const Frac &f1, const Frac &f2) {
  79. Frac ret = f1;
  80. ret += f2;
  81. return ret;
  82. }
  83.  
  84. Frac operator*(const Frac &f1, const Frac &f2) {
  85. Frac ret = f1;
  86. ret *= f2;
  87. return ret;
  88. }
  89.  
  90. int main() {
  91. Frac a(1, 2);
  92. Frac b(1, 3);
  93. Frac c = a + b;
  94. Frac d = a * b;
  95. Frac e = d * 15;
  96. Frac f = e.reduce();
  97. Frac g = f * 2;
  98. Frac h = g.reduce();
  99. printf("a = %s\n", a.str().c_str());
  100. printf("b = %s\n", b.str().c_str());
  101. printf("c = %s\n", c.str().c_str());
  102. printf("d = %s\n", d.str().c_str());
  103. printf("e = %s\n", e.str().c_str());
  104. printf("f = %s\n", f.str().c_str());
  105. printf("g = %s\n", g.str().c_str());
  106. printf("h = %s\n", h.str().c_str());
  107. }
  108.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
a = 1/2
b = 1/3
c = 5/6
d = 1/6
e = 15/6
f = 5/2
g = 10/2
h = 5