00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033 #ifndef _RATIONAL_H
00034 #define _RATIONAL_H
00035
00036 #include <iostream>
00037
00038 namespace Go {
00041
00042
00048 class Rational
00049 {
00050 public:
00051
00053 Rational() : p_(0), q_(1) {}
00054
00056 Rational(int p) : p_(p), q_(1) {}
00057
00059 Rational(int p, int q) : p_(p), q_(q) {}
00060
00062 Rational& operator += (const Rational& other)
00063 {
00064 p_ = p_*other.q_ + q_*other.p_;
00065 q_ = q_*other.q_;
00066 simplify();
00067 return *this;
00068 }
00069
00071 Rational& operator -= (const Rational& other)
00072 {
00073 Rational tmp = -other;
00074 (*this) += tmp;
00075 return *this;
00076 }
00077
00079 Rational& operator *= (const Rational& other)
00080 {
00081 p_ = p_*other.p_;
00082 q_ = q_*other.q_;
00083 simplify();
00084 return *this;
00085 }
00086
00088 Rational& operator /= (const Rational& other)
00089 {
00090 p_ = p_*other.q_;
00091 q_ = q_*other.p_;
00092 simplify();
00093 return *this;
00094 }
00095
00097 Rational operator- () const
00098 {
00099 return Rational(-p_, q_);
00100 }
00101
00103 bool operator == (const Rational r)
00104 {
00105 return (p_ == r.p_ && q_ == r.q_);
00106 }
00107
00109 bool operator != (const Rational r)
00110 {
00111 return (p_ != r.p_ || q_ != r.q_);
00112 }
00113
00115 void write(std::ostream& os) const
00116 {
00117 os << p_ << '/' << q_;
00118 }
00119
00121 void simplify()
00122 {
00123 int n = std::min(abs(p_), abs(q_));
00124 for (int i = 2; i <= n; ++i) {
00125 while (p_%i==0 && q_%i==0) {
00126 p_ /= i;
00127 q_ /= i;
00128 n /= i;
00129 }
00130 }
00131 }
00132
00133 private:
00134 int p_;
00135 int q_;
00136 };
00137
00138 Rational operator + (const Rational& r1, const Rational r2)
00139 {
00140 Rational res = r1;
00141 res += r2;
00142 return res;
00143 }
00144
00145 Rational operator - (const Rational& r1, const Rational r2)
00146 {
00147 Rational res = r1;
00148 res -= r2;
00149 return res;
00150 }
00151
00152 Rational operator * (const Rational& r1, const Rational r2)
00153 {
00154 Rational res = r1;
00155 res *= r2;
00156 return res;
00157 }
00158
00159 Rational operator / (const Rational& r1, const Rational r2)
00160 {
00161 Rational res = r1;
00162 res /= r2;
00163 return res;
00164 }
00165
00166 std::ostream& operator << (std::ostream& os, const Rational& p)
00167 {
00168 p.write(os);
00169 return os;
00170 }
00171
00173 };
00174 #endif // _RATIONAL_H
00175
00176