Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- int gcd(int a, int b) { return 1; }
- #define EQ_OP(T, BODY) \
- bool operator ==(const T& other) const { BODY; } \
- bool operator !=(const T& other) const { return !(*this == other); }
- #define ASS_OP(T, OP, BODY) T& operator OP(const T& other) { BODY return *this; }
- #define ARITHM_OP(T, OP) const T operator OP(const T& other) const { return T(*this) OP ## = other; }
- class Rational {
- private:
- typedef Rational T;
- void normalize() { int d = gcd(num, den); num /= d; den /= d; }
- public:
- int num, den;
- Rational() : num(0), den(1) {}
- Rational(int n) : num(n), den(1) {}
- Rational(int num, int den) : num(num), den(den) {}
- explicit operator double() const { return (double)num / (double)den; }
- explicit operator int() const { return (int)(double)(*this); }
- EQ_OP(T, return num * other.den == other.num * den;)
- ASS_OP(T, +=, num = num * other.den + other.num * den; den *= other.den; normalize();)
- ASS_OP(T, -=, num = num * other.den - other.num * den; den *= other.den; normalize();)
- ASS_OP(T, *=, num *= other.num; den *= other.den; normalize();)
- ASS_OP(T, /=, num *= other.den; den *= other.num; normalize();)
- ARITHM_OP(T, +)
- ARITHM_OP(T, -)
- ARITHM_OP(T, *)
- ARITHM_OP(T, /)
- };
- template<typename R, int N>
- class RingExtension {
- typedef RingExtension<R, N> T;
- public:
- R a, b;
- RingExtension<R, N>() : a(0), b(0) {}
- RingExtension<R, N>(R a) : a(a), b(0) {}
- RingExtension<R, N>(R a, R b) : a(a), b(b) {}
- explicit operator double() const { return (double)a + (double)b * sqrt(N); }
- explicit operator int() const { return (int)(double)*this; }
- EQ_OP(T, return a == other.a && b == other.b; )
- ASS_OP(T, +=, a += other.a; b += other.b;)
- ASS_OP(T, -=, a -= other.a; b -= other.b;)
- ASS_OP(T, *=,
- R aa = a * other.a + b * other.b * N;
- R bb = a * other.b + b * other.a;
- a = aa;
- b = bb;
- )
- ASS_OP(T, /=,
- R den = other.a * other.a - other.b * other.b * N;
- R aa = (a * other.a - b * other.b * N) / den;
- R bb = (b * other.a - a * other.b) / den;
- a = aa;
- b = bb;
- )
- ARITHM_OP(T, +)
- ARITHM_OP(T, -)
- ARITHM_OP(T, *)
- ARITHM_OP(T, / )
- };
- typedef RingExtension<int, -1> GaussianInt; //works, except for conversions
- int main() {
- RingExtension<Rational, 2> x = 3;
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement