jpp/lab2/zad1/include/GF.hpp

112 lines
2.5 KiB
C++
Raw Normal View History

2024-04-11 20:23:13 +02:00
#pragma once
#include <cinttypes>
#include <compare>
#include <sstream>
template<uint N>
class GF {
uint value;
public:
std::strong_ordering operator<=>(const GF<N> &rhs) const = default;
GF<N> &operator=(const GF<N> &value) = default;
GF()
: value(0u) {}
GF(const uint &value)
: value(value % N) {}
GF<N> &operator=(const uint &value) {
this->value = value % N;
return *this;
}
GF<N> operator+(const GF<N> &rhs) const {
return (this->value + rhs.value) % N;
}
GF<N> operator+(const uint &rhs) const {
return this->operator+(GF<N>(rhs));
}
GF<N> operator-(const GF<N> &rhs) const {
if (this->value < rhs.value) {
return N - (rhs.value - this->value);
}
return (this->value - rhs.value);
}
GF<N> operator-(const uint &rhs) const {
return this->operator-(GF<N>(rhs));
}
GF<N> operator*(const GF<N> &rhs) const {
return (this->value * rhs.value) % N;
}
GF<N> operator*(const uint &rhs) const {
return this->operator*(GF<N>(rhs));
}
GF<N> operator/(const GF<N> &rhs) const {
if (rhs.value == 0) {
throw std::invalid_argument("division by 0 is illegal");
}
return (this->value / rhs.value) % N;
}
GF<N> operator/(const uint &rhs) const {
return this->operator/(GF<N>(rhs));
}
GF<N> operator+=(const GF<N> &rhs) {
*this = *this + rhs;
return *this;
}
GF<N> operator+=(const uint &rhs) {
return this->operator+=(GF<N>(rhs));
}
GF<N> operator-=(const GF<N> &rhs) {
*this = *this - rhs;
return *this;
}
GF<N> operator-=(const uint &rhs) {
return this->operator-=(GF<N>(rhs));
}
GF<N> operator*=(const GF<N> &rhs) {
*this = *this * rhs;
return *this;
}
GF<N> operator*=(const uint &rhs) {
return this->operator*=(GF<N>(rhs));
}
GF<N> operator/=(const GF<N> &rhs) {
*this = *this / rhs;
return *this;
}
GF<N> operator/=(const uint &rhs) {
return this->operator/=(GF<N>(rhs));
}
friend std::ostream &operator<<(std::ostream &stream, const GF<N> &value) {
stream << "GF<" << N << ">(" << value.value << ")";
return stream;
}
friend std::istream &operator>>(std::istream &stream, GF<N> &value) {
stream >> value.value;
return stream;
}
uint characteristic() { return N; };
};