c++ lab2 improvements

This commit is contained in:
jacekpoz 2024-04-12 10:20:52 +02:00
parent eb3400fbc7
commit b217f2f5b8
Signed by: poz
SSH key fingerprint: SHA256:JyLeVWE4bF3tDnFeUpUaJsPsNlJyBldDGV/dIKSLyN8
2 changed files with 34 additions and 21 deletions

View file

@ -6,25 +6,25 @@
template<uint N>
class GF {
uint value;
uint _value;
public:
std::strong_ordering operator<=>(const GF<N> &rhs) const = default;
GF<N> &operator=(const GF<N> &value) = default;
GF()
: value(0u) {}
: _value(0u) {}
GF(const uint &value)
: value(value % N) {}
: _value(value % N) {}
GF<N> &operator=(const uint &value) {
this->value = value % N;
this->_value = value % N;
return *this;
}
GF<N> operator+(const GF<N> &rhs) const {
return (this->value + rhs.value) % N;
return (this->_value + rhs._value) % N;
}
GF<N> operator+(const uint &rhs) const {
@ -32,10 +32,10 @@ public:
}
GF<N> operator-(const GF<N> &rhs) const {
if (this->value < rhs.value) {
return N - (rhs.value - this->value);
if (this->_value < rhs._value) {
return N - (rhs._value - this->_value);
}
return (this->value - rhs.value);
return (this->_value - rhs._value);
}
GF<N> operator-(const uint &rhs) const {
@ -43,7 +43,7 @@ public:
}
GF<N> operator*(const GF<N> &rhs) const {
return (this->value * rhs.value) % N;
return (this->_value * rhs._value) % N;
}
GF<N> operator*(const uint &rhs) const {
@ -51,10 +51,19 @@ public:
}
GF<N> operator/(const GF<N> &rhs) const {
if (rhs.value == 0) {
if (rhs._value == 0) {
throw std::invalid_argument("division by 0 is illegal");
}
return (this->value / rhs.value) % N;
uint inverse = 1;
for (size_t i = 1; i < N; i++) {
if ((rhs._value * i) % N == 1) {
inverse = i;
break;
}
}
return GF<N>((this->_value * inverse) % N);
}
GF<N> operator/(const uint &rhs) const {
@ -97,15 +106,18 @@ public:
return this->operator/=(GF<N>(rhs));
}
friend std::ostream &operator<<(std::ostream &stream, const GF<N> &value) {
stream << "GF<" << N << ">(" << value.value << ")";
friend std::ostream &operator<<(std::ostream &stream, const GF<N> &val) {
stream << "GF<" << N << ">(" << val._value << ")";
return stream;
}
friend std::istream &operator>>(std::istream &stream, GF<N> &value) {
stream >> value.value;
friend std::istream &operator>>(std::istream &stream, GF<N> &val) {
stream >> val._value;
val._value %= N;
return stream;
}
uint characteristic() { return N; };
uint characteristic() const { return N; }
uint value() const { return _value; }
};

View file

@ -5,14 +5,15 @@
int main(void) {
GF<1234577> a = 3;
GF<1234577> a;
GF<1234577> b;
std::cin >> b;
std::cin >> a >> b;
a -= b;
std::cout << a << "\n";
std::cout << a << " + " << b << ": " << a + b << "\n";
std::cout << a << " - " << b << ": " << a - b << "\n";
std::cout << a << " * " << b << ": " << a * b << "\n";
std::cout << a << " / " << b << ": " << a / b << "\n";
return 0;
}