aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSebastiano Tronto <sebastiano@tronto.net>2024-12-21 17:54:02 +0100
committerSebastiano Tronto <sebastiano@tronto.net>2024-12-21 17:54:02 +0100
commit771667c2bb52235d6dacf67eab933207b59e167b (patch)
treeaa354ddae02f1a393771ba580febf8a33973d315
parent32cce8fe6a4b35d24d6a63b3226daee2a2753684 (diff)
downloadzmodn-771667c2bb52235d6dacf67eab933207b59e167b.tar.gz
zmodn-771667c2bb52235d6dacf67eab933207b59e167b.zip
Fix division
-rwxr-xr-xtest10
-rw-r--r--zmodn.h8
2 files changed, 15 insertions, 3 deletions
diff --git a/test b/test
index 4b426c2..d80dc2b 100755
--- a/test
+++ b/test
@@ -141,6 +141,16 @@ public:
141 assert_equal(p, 92); 141 assert_equal(p, 92);
142 } 142 }
143}, 143},
144{
145 .name = "4 / 2 mod 6",
146 .f = []() {
147 Zmod<6> four = 4;
148 Zmod<6> two = 2;
149 auto d = four / two;
150 assert_equal(d.has_value(), true);
151 assert_equal(d.value(), 2);
152 }
153},
144}; 154};
145 155
146int main() { 156int main() {
diff --git a/zmodn.h b/zmodn.h
index fdb1ee6..890fb0e 100644
--- a/zmodn.h
+++ b/zmodn.h
@@ -40,13 +40,15 @@ public:
40 bool operator!=(const Zmod& z) const { return value != z.value; } 40 bool operator!=(const Zmod& z) const { return value != z.value; }
41 41
42 std::optional<Zmod> inverse() const { 42 std::optional<Zmod> inverse() const {
43 auto [g, a, _] = extended_gcd(value, N); 43 auto [g, a, b] = extended_gcd(value, N);
44 return g == 1 ? Zmod(a) : std::optional<Zmod>{}; 44 return g == 1 ? Zmod(a) : std::optional<Zmod>{};
45 } 45 }
46 46
47 std::optional<Zmod> operator/(const Zmod& d) const { 47 std::optional<Zmod> operator/(const Zmod& d) const {
48 auto i = d.inverse(); 48 auto [g, x, y] = extended_gcd(value, d.toint());
49 return i ? (*this) * i.value() : i; 49 auto [a, b] = std::pair<Zmod, Zmod>{value / g, d.toint() / g};
50 auto i = b.inverse();
51 return i ? a * i.value() : i;
50 } 52 }
51 53
52 std::optional<Zmod> operator/=(const Zmod& d) { 54 std::optional<Zmod> operator/=(const Zmod& d) {