Overview
Numeric utilities provide essential tools for handling large numbers and modular arithmetic in competitive programming. These implementations prevent overflow and ensure correct results under modular constraints.Categories
Modular Arithmetic
Mint template for automatic modulo operations
Big Integer
Arbitrary precision integer implementation
Why Modular Arithmetic?
Many competitive programming problems ask for answers modulo a large prime (typically 10^9+7) to:- Prevent overflow: Results can be astronomically large
- Standardize answers: Multiple valid representations become unique
- Enable comparison: Same answers produce same modular values
- Test correctness: Large numbers are harder to verify
Common Moduli
Modular Operations
Basic Operations
Fast Exponentiation
Modular Inverse
For prime modulus, use Fermat’s Little Theorem:When to Use What
Use Mint Template When:
- Problem requires all operations modulo a fixed value
- You want automatic modular reduction
- Working with combinatorics or dynamic programming
- Need clean, readable code
Use BigInt When:
- Numbers exceed 64-bit range
- No modulo constraint given
- Exact arithmetic required
- Implementing number theory algorithms for large numbers
Use Built-in Types When:
- Numbers fit in
int(< 2×10^9) - Numbers fit in
long long(< 9×10^18) - Performance is critical and no special handling needed
Complexity Reference
| Operation | Mint | BigInt | Built-in |
|---|---|---|---|
| Addition | O(1) | O(n) | O(1) |
| Multiplication | O(1) | O(n²) or O(n log n)* | O(1) |
| Division | O(log MOD) | O(n²) | O(1) |
| Comparison | O(1) | O(n) | O(1) |
Common Pitfalls
1. Overflow Before Modulo
2. Negative Modulo
3. Division by Zero
4. Comparison After Modulo
Best Practices
-
Define constants clearly
-
Precompute factorials for combinatorics
-
Use type aliases for clarity
-
Test edge cases
- a = 0, b = 0
- a = MOD - 1 (negative after modulo)
- Very large intermediate results
-
Profile performance
- Mint adds overhead compared to raw int
- BigInt is much slower than built-in types
- Use appropriately based on constraints