Skip to content

Commit 95359a8

Browse files
committed
modint: add/sub impl fix for 2^31<modulus<2^32
1 parent d803958 commit 95359a8

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed

src/modint.rs

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -793,20 +793,20 @@ trait InternalImplementations: ModIntBase {
793793
#[inline]
794794
fn add_impl(lhs: Self, rhs: Self) -> Self {
795795
let modulus = Self::modulus();
796-
let mut val = lhs.val() + rhs.val();
797-
if val >= modulus {
798-
val -= modulus;
799-
}
796+
let val = match lhs.val().overflowing_sub(modulus - rhs.val()) {
797+
(v, true) => v.wrapping_add(modulus),
798+
(v, false) => v,
799+
};
800800
Self::raw(val)
801801
}
802802

803803
#[inline]
804804
fn sub_impl(lhs: Self, rhs: Self) -> Self {
805805
let modulus = Self::modulus();
806-
let mut val = lhs.val().wrapping_sub(rhs.val());
807-
if val >= modulus {
808-
val = val.wrapping_add(modulus)
809-
}
806+
let val = match lhs.val().overflowing_sub(rhs.val()) {
807+
(v, true) => v.wrapping_add(modulus),
808+
(v, false) => v,
809+
};
810810
Self::raw(val)
811811
}
812812

@@ -1050,6 +1050,7 @@ impl_folding! {
10501050

10511051
#[cfg(test)]
10521052
mod tests {
1053+
use crate::modint::ModInt;
10531054
use crate::modint::ModInt1000000007;
10541055

10551056
#[test]
@@ -1157,4 +1158,28 @@ mod tests {
11571158
c /= b;
11581159
assert_eq!(expected, c);
11591160
}
1161+
1162+
// test `2^31 < modulus < 2^32` case.
1163+
#[test]
1164+
fn dynamic_modint_m32() {
1165+
let m = 3221225471;
1166+
ModInt::set_modulus(m);
1167+
let f = ModInt::new::<u32>;
1168+
assert_eq!(f(1398188832) + f(3184083880), f(1361047241));
1169+
assert_eq!(f(3013899062) + f(2238406135), f(2031079726));
1170+
assert_eq!(f(2699997885) + f(2745140255), f(2223912669));
1171+
assert_eq!(f(2824399978) + f(2531872141), f(2135046648));
1172+
assert_eq!(f(36496612) - f(2039504668), f(1218217415));
1173+
assert_eq!(f(266176802) - f(1609833977), f(1877568296));
1174+
assert_eq!(f(713535382) - f(2153383999), f(1781376854));
1175+
assert_eq!(f(1249965147) - f(3144251805), f(1326938813));
1176+
assert_eq!(f(2692223381) * f(2935379475), f(2084179397));
1177+
assert_eq!(f(2800462205) * f(2822998916), f(2089431198));
1178+
assert_eq!(f(3061947734) * f(3210920667), f(1962208034));
1179+
assert_eq!(f(3138997926) * f(2994465129), f(1772479317));
1180+
assert_eq!(f(2947552629) / f(576466398), f(2041593039));
1181+
assert_eq!(f(2914694891) / f(399734126), f(1983162347));
1182+
assert_eq!(f(2202862138) / f(1154428799), f(2139936238));
1183+
assert_eq!(f(3037207894) / f(2865447143), f(1894581230));
1184+
}
11601185
}

0 commit comments

Comments
 (0)