From fb08d9ff9e7264d91850a1042ab3d6db39044310 Mon Sep 17 00:00:00 2001 From: nicoo Date: Thu, 18 Jun 2020 13:01:55 +0200 Subject: [PATCH] factor::numeric::Montgomery::add: Deal with rare overflow case --- src/uu/factor/src/numeric.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/uu/factor/src/numeric.rs b/src/uu/factor/src/numeric.rs index c0f9d9f47..4e0cee072 100644 --- a/src/uu/factor/src/numeric.rs +++ b/src/uu/factor/src/numeric.rs @@ -123,7 +123,17 @@ impl Arithmetic for Montgomery { } fn add(&self, a: Self::I, b: Self::I) -> Self::I { - let r = a + b; + let (r, overflow) = a.overflowing_add(b); + + // In case of overflow, a+b = 2⁶⁴ + r = (2⁶⁴ - n) + r (working mod n) + let r = if !overflow { + r + } else { + r + self.n.wrapping_neg() + }; + + // Normalise to [0; n[ + let r = if r < self.n { r } else { r - self.n }; // Check that r (reduced back to the usual representation) equals // a+b % n