Modular Arithmetic Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Modular Arithmetic runs in O(log n) time and O(1) space, in Rust as in every other language.
- ✓Every integer primitive has BOTH % (Rem, truncating toward zero like C) and rem_euclid, added to the standard library specifically to give the always-non-negative floored result: (-7i32).rem_euclid(3) == 2, matching Python's %, while -7 % 3 == -1 with the default operator.
- ✓Use rem_euclid everywhere a value can go negative, and reserve the plain % operator for cases where the operands are provably non-negative or truncating semantics are specifically wanted -- reaching for rem_euclid by default is what an experienced reviewer expects in any modular-arithmetic function.
- ✓The Rust trap: The plain % operator PANICS on i32::MIN % -1 -- a genuine edge case where the mathematical result overflows the type -- which is easy to miss because every other combination of operands works fine; code that mods user-controlled or adversarial input without going through rem_euclid or checked_rem can crash in production on that one specific pair.
- ✓rem_euclid compiles to the same single hardware division instruction as %, plus a conditional add-and-compare to fix the sign when the result was negative -- effectively free, not a second division.
What Modular Arithmetic actually is
Modular Arithmetic in Rust: what you actually reach for
Rust implementation
use num_integer::{Integer, ExtendedGcd};
fn mod_add(a: i64, b: i64, m: i64) -> i64 {
(a + b).rem_euclid(m) // always in [0, m) - unlike the bare % operator
}
fn mod_inverse(a: i64, m: i64) -> Option<i64> {
let ExtendedGcd { gcd, x, .. } = a.extended_gcd(&m); // Bezout: a*x + m*y == gcd
if gcd != 1 { return None; }
Some(x.rem_euclid(m))
}
fn main() {
assert_eq!((-7i64).rem_euclid(3), 2);
assert_eq!(-7i64 % 3, -1); // the default operator: truncated, sign follows dividend
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Modular Arithmetic?
Every integer primitive has BOTH % (Rem, truncating toward zero like C) and rem_euclid, added to the standard library specifically to give the always-non-negative floored result: (-7i32).rem_euclid(3) == 2, matching Python's %, while -7 % 3 == -1 with the default operator. There is no modular-inverse function on primitives; the num-integer crate's Integer::extended_gcd returns an ExtendedGcd { gcd, x, y } struct satisfying a*x + m*y == gcd, the well-known crate answer for an inverse on primitives or, via num-bigint, at arbitrary precision.
What is the most common Rust mistake when implementing Modular Arithmetic?
The plain % operator PANICS on i32::MIN % -1 -- a genuine edge case where the mathematical result overflows the type -- which is easy to miss because every other combination of operands works fine; code that mods user-controlled or adversarial input without going through rem_euclid or checked_rem can crash in production on that one specific pair. rem_euclid panics for exactly the same reason on the same input, since the true result still does not fit, so switching to it fixes the SIGN problem but not this one.
How does Modular Arithmetic actually perform in Rust?
rem_euclid compiles to the same single hardware division instruction as %, plus a conditional add-and-compare to fix the sign when the result was negative -- effectively free, not a second division. num_integer::extended_gcd is O(log(min(a, m))) exactly like the extended Euclidean algorithm anywhere else, generic and monomorphized so it inlines for primitive integer types with no allocation, and only allocates once instantiated over BigInt. Time complexity is O(log n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.