Binary Exponentiation Implementation in C#
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 C# as in every other language.
- ✓System.Numerics.BigInteger.ModPow(value, exponent, modulus) is the direct standard-library equivalent of Java's modPow, implemented with an internal windowed algorithm rather than one-bit-at-a-time squaring.
- ✓Reach for BigInteger.ModPow for anything beyond safe long range, and be explicit about checked vs unchecked context for a hand-rolled long-based loop, since C# lets that be chosen per-expression or per-block with the checked/unchecked keywords rather than picking one policy per build profile the way Rust does.
- ✓The C# trap: C# exposes BOTH overflow policies as an explicit choice, not a build-configuration side effect: the SAME multiplication that silently wraps in an unchecked context (the default for runtime arithmetic) throws System.OverflowException the moment it is wrapped in a checked { } block or the project is compiled with /checked+.
- ✓BigInteger.ModPow's windowed internal algorithm needs fewer modular multiplications than a naive one-bit loop for the same exponent, and BigInteger's operations are allocation-heavy since it wraps an internal array -- worth it once operands exceed 64 bits, wasteful below that.
What Binary Exponentiation actually is
Binary Exponentiation in C#: what you actually reach for
C# implementation
using System.Numerics;
static ulong BinPow(ulong baseVal, ulong exp, ulong mod) {
ulong result = 1 % mod;
baseVal %= mod;
unchecked { // explicit: this loop relies on wraparound never happening
while (exp > 0) {
if ((exp & 1) == 1) result = result * baseVal % mod;
baseVal = baseVal * baseVal % mod;
exp >>= 1;
}
}
return result;
}
BigInteger modexp = BigInteger.ModPow(3, 200, 1_000_000_007); // windowed algorithm internallyThink 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 C#-specific trap
Performance in C#, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Binary Exponentiation?
System.Numerics.BigInteger.ModPow(value, exponent, modulus) is the direct standard-library equivalent of Java's modPow, implemented with an internal windowed algorithm rather than one-bit-at-a-time squaring. For fixed-width exponentiation there is no modular form on long/ulong -- Math.Pow only takes and returns double.
What is the most common C# mistake when implementing Binary Exponentiation?
C# exposes BOTH overflow policies as an explicit choice, not a build-configuration side effect: the SAME multiplication that silently wraps in an unchecked context (the default for runtime arithmetic) throws System.OverflowException the moment it is wrapped in a checked { } block or the project is compiled with /checked+. A hand-rolled squaring loop developed and tested in one context can behave completely differently -- silent wrong answer vs. a thrown exception -- if the calling code's checked/unchecked context changes without the loop itself changing at all.
How does Binary Exponentiation actually perform in C#?
BigInteger.ModPow's windowed internal algorithm needs fewer modular multiplications than a naive one-bit loop for the same exponent, and BigInteger's operations are allocation-heavy since it wraps an internal array -- worth it once operands exceed 64 bits, wasteful below that. An unchecked ulong loop with mod after every multiply has zero allocation and no overflow-check overhead, and is the fastest option whenever the modulus provably keeps every intermediate under ulong.MaxValue. 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? GitHub Copilot 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.