Binary Exponentiation 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
- ✓Binary Exponentiation runs in O(log n) time and O(1) space, in Rust as in every other language.
- ✓u32::pow / u64::pow and friends exist but only compute the UNMODDED power in the type's own width, panicking on overflow in a debug build and silently wrapping (two's-complement) in a release build -- neither behavior is modular exponentiation.
- ✓For fixed-width modular exponentiation under a modulus you control (the classic competitive-programming 1e9+7), hand-write the squaring loop over u64 with wrapping_mul, since the modulus keeps every intermediate below it and a checked or panicking multiply is unnecessary overhead once that bound is proven.
- ✓The Rust trap: A debug build panics on integer overflow (attempt to multiply with overflow) while the SAME code compiled --release silently wraps mod 2^64 and returns a plausible but wrong number with no panic at all.
- ✓The u64 wrapping_mul loop is fastest when the modulus fits in 32 bits (so its square fits in 64), doing exactly log2(exp) squarings with zero heap allocation and full inlining.
What Binary Exponentiation actually is
Binary Exponentiation in Rust: what you actually reach for
Rust implementation
fn bin_pow_u64(mut base: u64, mut exp: u64, modulus: u64) -> u64 {
let mut result = 1u64 % modulus;
base %= modulus;
while exp > 0 {
if exp & 1 == 1 {
result = result.wrapping_mul(base) % modulus; // wrap is fine, we mod right after
}
base = base.wrapping_mul(base) % modulus;
exp >>= 1;
}
result
}
// arbitrary-precision path when the modulus itself does not fit in u64
use num_bigint::BigUint;
fn bin_pow_big(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint {
base.modpow(exp, modulus)
}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 Binary Exponentiation?
u32::pow / u64::pow and friends exist but only compute the UNMODDED power in the type's own width, panicking on overflow in a debug build and silently wrapping (two's-complement) in a release build -- neither behavior is modular exponentiation. The real modPow lives in the num-bigint crate: BigUint::modpow(&exponent, &modulus) is arbitrary-precision binary exponentiation with the modulus folded in at every squaring, the direct equivalent of Java's or Go's builtin.
What is the most common Rust mistake when implementing Binary Exponentiation?
A debug build panics on integer overflow (attempt to multiply with overflow) while the SAME code compiled --release silently wraps mod 2^64 and returns a plausible but wrong number with no panic at all. A hand-rolled u64 squaring loop that forgets to reduce mod m after EVERY multiply -- not just at the end -- will pass every debug-mode test (because a small modulus means overflow never triggers there) and then silently corrupt results in release once an intermediate exceeds u64::MAX, since release wraps instead of crashing.
How does Binary Exponentiation actually perform in Rust?
The u64 wrapping_mul loop is fastest when the modulus fits in 32 bits (so its square fits in 64), doing exactly log2(exp) squarings with zero heap allocation and full inlining. BigUint::modpow allocates a Vec<u32> of limbs for every intermediate value, so it is correct for arbitrarily large moduli but measurably slower per multiplication than the fixed-width loop for anything that would have fit in a u64. 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 trialBefore paying for Replit, check its student and free-tier options 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.