commit b0d8a2f5f5718ba3fea628cad7bcbbc76c6a140c
parent 4d9b0b7cb5c749cd1db3828ab9a3475e6c9811b6
Author: Sebastiano Tronto <sebastiano@tronto.net>
Date: Sat, 21 Dec 2024 16:19:39 +0100
Fix possible overflow with assignment operations
Diffstat:
2 files changed, 21 insertions(+), 3 deletions(-)
diff --git a/test b/test
@@ -115,6 +115,24 @@ public:
assert_equal(n, Zmod<12>(4));
}
},
+{
+ .name = "Multiplication overflow",
+ .f = []() {
+ Zmod<10> n = 8;
+ Zmod<10> m = 9;
+ auto prod = m * n;
+ assert_equal(prod.toint64(), 2);
+ }
+},
+{
+ .name = "Multiplication and assignment overflow",
+ .f = []() {
+ Zmod<10> n = 8;
+ Zmod<10> m = 9;
+ n *= m;
+ assert_equal(n.toint64(), 2);
+ }
+},
};
int main() {
diff --git a/zmodn.h b/zmodn.h
@@ -17,9 +17,9 @@ public:
Zmod operator+(const Zmod& z) const { return int64 + z.int64; }
Zmod operator-(const Zmod& z) const { return int64 - z.int64; }
Zmod operator*(const Zmod& z) const { return int64 * z.int64; }
- Zmod operator+=(const Zmod& z) { return int64 += z.int64; }
- Zmod operator-=(const Zmod& z) { return int64 -= z.int64; }
- Zmod operator*=(const Zmod& z) { return int64 *= z.int64; }
+ Zmod operator+=(const Zmod& z) { return (*this) = int64 + z.int64; }
+ Zmod operator-=(const Zmod& z) { return (*this) = int64 - z.int64; }
+ Zmod operator*=(const Zmod& z) { return (*this) = int64 * z.int64; }
bool operator==(const Zmod& z) const { return int64 == z.int64; }
bool operator!=(const Zmod& z) const { return int64 != z.int64; }