-
Notifications
You must be signed in to change notification settings - Fork 0
/
Modular.h
116 lines (92 loc) · 2.84 KB
/
Modular.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#pragma once
#include <iostream>
#include <numeric>
#include "Diophantine.h"
namespace Groebner {
template <std::int64_t mod>
class Modular {
static_assert(mod > 0, "The modulus must be positive!");
public:
using IntegralType = std::int64_t;
Modular() = default;
Modular(IntegralType number) : number_(number) {
reduce();
}
IntegralType canonical_remainder() const {
return number_;
}
Modular operator+() const {
return *this;
}
Modular operator-() const {
return Modular(-number_);
}
Modular& operator+=(const Modular& other) {
number_ += other.number_;
reduce();
return *this;
}
Modular& operator-=(const Modular& other) {
number_ -= other.number_;
reduce();
return *this;
}
Modular& operator*=(const Modular& factor) {
number_ *= factor.number_;
reduce();
return *this;
}
Modular& operator/=(const Modular& divider) {
auto solution = Equations::solve_equation<IntegralType>(divider.number_, mod, number_);
number_ = solution.first_coefficient;
reduce();
return *this;
}
friend Modular operator+(const Modular& first, const Modular& second) {
Modular result = first;
result += second;
return result;
}
friend Modular operator-(const Modular& first, const Modular& second) {
Modular result = first;
result -= second;
return result;
}
friend Modular operator*(const Modular& first, const Modular& second) {
Modular result = first;
result *= second;
return result;
}
friend Modular operator/(const Modular& first, const Modular& second) {
Modular result = first;
result /= second;
return result;
}
friend bool operator==(const Modular& first, const Modular& second) {
return first.canonical_remainder() == second.canonical_remainder();
}
friend bool operator!=(const Modular& first, const Modular& second) {
return !(first == second);
}
friend bool operator<(const Modular& first, const Modular& second) {
return first.canonical_remainder() < second.canonical_remainder();
}
friend bool operator>(const Modular& first, const Modular& second) {
return second < first;
}
friend bool operator<=(const Modular& first, const Modular& second) {
return !(first > second);
}
friend bool operator>=(const Modular& first, const Modular& second) {
return !(first < second);
}
friend std::ostream& operator<<(std::ostream& out, const Modular& current) {
return out << current.canonical_remainder();
}
private:
void reduce() {
number_ = ((number_ % mod) + mod) % mod;
}
IntegralType number_ = 0;
};
} // namespace Groebner