|
| 1 | +#pragma once |
| 2 | +#include <cassert> |
| 3 | +#include <utility> |
| 4 | + |
| 5 | +struct GaussianInteger { |
| 6 | + using Int = long long; |
| 7 | + using G = GaussianInteger; |
| 8 | + Int x, y; // x + yi |
| 9 | + |
| 10 | + Int re() const noexcept { return x; } |
| 11 | + Int im() const noexcept { return y; } |
| 12 | + |
| 13 | + explicit GaussianInteger(Int x_ = 0, Int y_ = 0) : x(x_), y(y_) {} |
| 14 | + |
| 15 | + G &operator+=(const G &n) { |
| 16 | + x += n.x, y += n.y; |
| 17 | + return *this; |
| 18 | + } |
| 19 | + G &operator-=(const G &n) { |
| 20 | + x -= n.x, y -= n.y; |
| 21 | + return *this; |
| 22 | + } |
| 23 | + G &operator*=(const G &n) { |
| 24 | + const Int nx = x * n.x - y * n.y, ny = x * n.y + y * n.x; |
| 25 | + x = nx, y = ny; |
| 26 | + return *this; |
| 27 | + } |
| 28 | + |
| 29 | + // Euclidean division |
| 30 | + G &operator/=(const G &n) { |
| 31 | + const Int d = n.norm(); |
| 32 | + assert(d != 0); |
| 33 | + const Int nx = x * n.x + y * n.y, ny = y * n.x - x * n.y; |
| 34 | + auto div_round = [](Int num, Int den) { |
| 35 | + return (num >= 0) ? (num + den / 2) / den : (num - den / 2) / den; |
| 36 | + }; |
| 37 | + x = div_round(nx, d), y = div_round(ny, d); |
| 38 | + return *this; |
| 39 | + } |
| 40 | + |
| 41 | + G &operator%=(const G &n) { |
| 42 | + *this -= (*this / n) * n; |
| 43 | + return *this; |
| 44 | + } |
| 45 | + |
| 46 | + G operator+(const G &n) const { return G(*this) += n; } |
| 47 | + G operator-(const G &n) const { return G(*this) -= n; } |
| 48 | + G operator*(const G &n) const { return G(*this) *= n; } |
| 49 | + G operator/(const G &n) const { return G(*this) /= n; } |
| 50 | + G operator%(const G &n) const { return G(*this) %= n; } |
| 51 | + |
| 52 | + Int norm() const { return x * x + y * y; } |
| 53 | + |
| 54 | + G conj() const { return G{x, -y}; } |
| 55 | + |
| 56 | + static G gcd(G a, G b) { |
| 57 | + while (b.x != 0 or b.y != 0) { |
| 58 | + a %= b; |
| 59 | + std::swap(a, b); |
| 60 | + } |
| 61 | + return a.canonical(); |
| 62 | + } |
| 63 | + friend G gcd(G a, G b) { return G::gcd(a, b); } |
| 64 | + |
| 65 | + bool operator==(const G &n) const { return x == n.x and y == n.y; } |
| 66 | + bool operator!=(const G &n) const { return !(*this == n); } |
| 67 | + |
| 68 | + template <class OStream> friend OStream &operator<<(OStream &os, const G &g) { |
| 69 | + return os << g.x << (g.y >= 0 ? "+" : "") << g.y << "i"; |
| 70 | + } |
| 71 | + |
| 72 | + // move to first quadrant (x > 0, y >= 0) |
| 73 | + G canonical() const { |
| 74 | + if (x > 0 and y >= 0) return *this; |
| 75 | + if (x <= 0 and y > 0) return G{y, -x}; |
| 76 | + if (x < 0 and y <= 0) return G{-x, -y}; |
| 77 | + return G{-y, x}; |
| 78 | + } |
| 79 | + |
| 80 | + std::pair<Int, Int> to_pair() const { return {x, y}; } |
| 81 | +}; |
0 commit comments