mirror of
https://github.com/RGBCube/uutils-coreutils
synced 2025-07-30 04:27:45 +00:00
factor::numeric::Montgomery::add: Deal with rare overflow case
This commit is contained in:
parent
d1470dadf8
commit
fb08d9ff9e
1 changed files with 11 additions and 1 deletions
|
@ -123,7 +123,17 @@ impl Arithmetic for Montgomery {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add(&self, a: Self::I, b: Self::I) -> Self::I {
|
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
|
// Check that r (reduced back to the usual representation) equals
|
||||||
// a+b % n
|
// a+b % n
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue