Skip to content

Instantly share code, notes, and snippets.

@GoBigorGoHome
Created December 18, 2018 01:34
Show Gist options
  • Save GoBigorGoHome/a28931445c8ff0cca98f59096489c512 to your computer and use it in GitHub Desktop.
Save GoBigorGoHome/a28931445c8ff0cca98f59096489c512 to your computer and use it in GitHub Desktop.
struct frac{
using ll = long long;
ll fz, fm;
frac() = default;
frac(ll fz, ll fm) { // 构造函数变量名最好不要跟类成员名一样!
assert(fm != 0);
if (fm < 0) fm *= -1, fz *= -1;
ll g = __gcd(abs(fz), fm);
fz /= g, fm /= g;
this->fz = fz, this->fm = fm;
}
frac(ll x):fz(x),fm(1){} // implicit conversion
frac operator*(const frac &other)const{
return {fz * other.fz, fm * other.fm};
}
frac operator-()const{
return {-fz, fm};
}
frac operator-(const frac &other)const{
return *this + (-other);
}
frac operator+(const frac &other)const{
ll _fz = fz * other.fm + fm * other.fz;
ll _fm = fm * other.fm;
return {_fz, _fm};
}
bool operator==(const frac &other)const{
return other.fz == fz && other.fm == fm;
}
bool operator<(const frac &other)const{
return fz * other.fm < other.fz * fm;
}
bool operator>(const frac &other)const{
return fz * other.fm > other.fz * fm;
}
bool operator>=(const frac &other)const{
return !(*this < other);
}
bool operator<=(const frac &other)const{
return !(*this > other);
}
frac operator/(const int &x)const{
return {fz, fm * x};
}
double to_double() const {
return fz / (double)fm;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment