Modular Arithmetic Implementation in TypeScript
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 TypeScript as in every other language.
- ✓Runtime is identical to JavaScript -- the same truncating %, no floorMod, no BigInt modInverse builtin.
- ✓Wrap every modular value in a branded/nominal type per modulus rather than passing raw numbers around -- structural typing alone means a value mod 1_000_000_007 and a value mod 998_244_353 are both just 'number', and TypeScript will happily let them be added, which is mathematically meaningless.
- ✓The TypeScript trap: Branding is ERASED at runtime exactly like every other TypeScript type -- it prevents mixing a Mod<1_000_000_007> and a Mod<998_244_353> at COMPILE time, but does nothing once a value crosses a JSON.stringify/parse boundary (an API response, localStorage, a worker message), where the brand is silently stripped and a plain unbranded number comes back with no warning.
- ✓Zero runtime cost for the branding itself -- it is a type-level intersection that tsc erases completely, so a Mod<M> value is exactly the same JavaScript number underneath with the identical O(log m) extended-Euclidean cost as the untyped version.
What Modular Arithmetic actually is
Modular Arithmetic in TypeScript: what you actually reach for
TypeScript implementation
type Mod<M extends number> = number & { readonly __mod: M };
function mod<M extends number>(n: number, m: M): Mod<M> {
return (((n % m) + m) % m) as Mod<M>;
}
function modAdd<M extends number>(a: Mod<M>, b: Mod<M>, m: M): Mod<M> {
return mod(a + b, m);
}
const p = 1_000_000_007;
const a = mod(-7, p); // branded Mod<1000000007>, already normalized to positive
// modAdd(a, mod(3, 998_244_353), p); // compile error: Mod<998244353> not assignable to Mod<1000000007>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 TypeScript-specific trap
Performance in TypeScript, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Modular Arithmetic?
Runtime is identical to JavaScript -- the same truncating %, no floorMod, no BigInt modInverse builtin. The type layer's real contribution is being able to brand a value with the modulus it was computed under: type Mod<M extends number> = number & { readonly __mod: M } prevents accidentally combining two values reduced under different moduli, something plain JavaScript has no way to catch even in principle.
What is the most common TypeScript mistake when implementing Modular Arithmetic?
Branding is ERASED at runtime exactly like every other TypeScript type -- it prevents mixing a Mod<1_000_000_007> and a Mod<998_244_353> at COMPILE time, but does nothing once a value crosses a JSON.stringify/parse boundary (an API response, localStorage, a worker message), where the brand is silently stripped and a plain unbranded number comes back with no warning. Treat branding as a discipline enforced at the edges of your own code, not a runtime guarantee.
How does Modular Arithmetic actually perform in TypeScript?
Zero runtime cost for the branding itself -- it is a type-level intersection that tsc erases completely, so a Mod<M> value is exactly the same JavaScript number underneath with the identical O(log m) extended-Euclidean cost as the untyped version. The only overhead is calling the smart-constructor function at each normalization point, which is a plain function call, not a wrapper object. 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 full price for a tool, check the student deals on AI and developer tools listed 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.