From cb03157987c27d18cdf8de7b3d30b09b695f755f Mon Sep 17 00:00:00 2001 From: subcrip Date: Sat, 16 Nov 2024 07:48:23 +0000 Subject: [PATCH] Add number/fractional.cc Signed-off-by: subcrip --- number/fractional.cc | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 number/fractional.cc diff --git a/number/fractional.cc b/number/fractional.cc new file mode 100644 index 0000000..2893953 --- /dev/null +++ b/number/fractional.cc @@ -0,0 +1,31 @@ +template +inline T mygcd(T a, T b) { return b == 0 ? a : mygcd(b, a % b); } + +template +struct fractional { + T p, q; + inline void reduce(void) { + if (q < 0) p = -p, q = -q; + if (p == 0) q = 1; else { T g = mygcd(p, q); p /= g; q /= g; } + } + fractional(void) : p(0), q(1) {} + template + fractional(const U& p) : p(p), q(1) { reduce(); } + fractional(const T& p, const T& q) : p(p), q(q) { reduce(); } + inline fractional operator+(void) const { return *this; } + inline fractional operator-(void) const { return { -p, q }; } + inline fractional operator+(const fractional& rhs) const { return { p * rhs.q + q * rhs.p, q * rhs.q }; } + inline fractional operator-(const fractional& rhs) const { return *this + (-rhs); } + inline fractional operator*(const fractional& rhs) const { return { p * rhs.p, q * rhs.q }; } + inline fractional operator/(const fractional& rhs) const { return *this * fractional(rhs.q, rhs.p); } + inline fractional& operator+=(const fractional& rhs) { return *this = *this + rhs; } + inline fractional& operator-=(const fractional& rhs) { return *this = *this - rhs; } + inline fractional& operator*=(const fractional& rhs) { return *this = *this * rhs; } + inline fractional& operator/=(const fractional& rhs) { return *this = *this / rhs; } + inline bool operator==(const fractional& rhs) const { return p == rhs.p and q == rhs.q; } + inline bool operator!=(const fractional& rhs) const { return not (*this == rhs); } + inline bool operator<(const fractional& rhs) const { return (*this - rhs).p < 0; } + inline bool operator>=(const fractional& rhs) const { return not (*this < rhs); } + inline bool operator>(const fractional& rhs) const { return *this >= rhs and *this != rhs; } + inline bool operator<=(const fractional& rhs) const { return *this < rhs or *this == rhs; } +};