Modular Arithmetic 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
- ✓Modular Arithmetic runs in O(log n) time and O(1) space, in C# as in every other language.
- ✓C#'s % is remainder, truncating toward zero, sign follows the dividend -- -7 % 3 == -1, same family as Java/Go/Swift/Rust's default.
- ✓Normalize by hand with (((a % m) + (b % m)) % m + m) % m for machine-width types, and be deliberate about the checked/unchecked context that normalization runs in, the same consideration as the exponentiation loop.
- ✓The C# trap: The absence of BigInteger.ModInverse is easy to miss because BigInteger.ModPow DOES exist and looks like a complete modular-arithmetic toolkit -- reaching for '.ModInverse' on autocomplete finds nothing, and falling back to computing it via ModPow with Fermat's little theorem (a^(m-2) mod m) without first checking the modulus is actually prime silently produces a wrong result for a composite modulus, exactly the same mistake as in Python or Go.
- ✓The hand-written extended Euclidean algorithm over BigInteger is O(log m) like every other implementation here, but BigInteger wraps an internal array, so each step's arithmetic allocates -- meaningful in a loop computing many inverses, at which point caching results or switching to a fixed-width ulong path (when the modulus fits) removes the allocation entirely.
What Modular Arithmetic actually is
Modular Arithmetic in C#: what you actually reach for
C# implementation
using System.Numerics;
static long ModAdd(long a, long b, long m) =>
(((a % m) + (b % m)) % m + m) % m; // truncating %, sign follows dividend
static BigInteger ModInverse(BigInteger a, BigInteger m) {
// BigInteger has ModPow but NO ModInverse - extended Euclid by hand
BigInteger oldR = a, r = m, oldS = 1, s = 0;
while (r != 0) {
BigInteger q = oldR / r;
(oldR, r) = (r, oldR - q * r);
(oldS, s) = (s, oldS - q * s);
}
if (oldR != 1) throw new ArgumentException("no inverse: gcd != 1");
return ((oldS % m) + m) % m;
}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 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 Modular Arithmetic?
C#'s % is remainder, truncating toward zero, sign follows the dividend -- -7 % 3 == -1, same family as Java/Go/Swift/Rust's default. There is no floorMod, and unlike Java's BigInteger, System.Numerics.BigInteger has no ModInverse method at all -- ModPow exists, but the inverse has to be hand-written via the extended Euclidean algorithm even at arbitrary precision.
What is the most common C# mistake when implementing Modular Arithmetic?
The absence of BigInteger.ModInverse is easy to miss because BigInteger.ModPow DOES exist and looks like a complete modular-arithmetic toolkit -- reaching for '.ModInverse' on autocomplete finds nothing, and falling back to computing it via ModPow with Fermat's little theorem (a^(m-2) mod m) without first checking the modulus is actually prime silently produces a wrong result for a composite modulus, exactly the same mistake as in Python or Go.
How does Modular Arithmetic actually perform in C#?
The hand-written extended Euclidean algorithm over BigInteger is O(log m) like every other implementation here, but BigInteger wraps an internal array, so each step's arithmetic allocates -- meaningful in a loop computing many inverses, at which point caching results or switching to a fixed-width ulong path (when the modulus fits) removes the allocation entirely. 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 Devin, 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.