Modular Arithmetic
Tutorial Video
Text description (accessibility)
This video demonstrates the "Modular Arithmetic" functional Rust example. Difficulty level: Intermediate. Key concepts covered: Functional Programming. When computing large combinatorial values (n! Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
When computing large combinatorial values (n! mod p, binomial coefficients, number of paths), intermediate results overflow 64-bit integers long before the final answer. Modular arithmetic performs all operations in a finite field Z/pZ, keeping values bounded. Computing (a + b) % m, (a * b) % m, pow(a, b, m), and inv(a, m) are the building blocks of competitive programming, cryptography, and number theory. The key insight: (a * b) % m = ((a % m) * (b % m)) % m. Modular exponentiation (fast power) runs in O(log b) and is essential for RSA, Diffie-Hellman, and primality testing.
🎯 Learning Outcomes
Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Overflow risk | u64 * u64 overflows above 2^32 mod | int * int overflows above 2^30 mod |
| Large modulus | Use u128 intermediate | Use Int64 or Zarith |
| Mod exponentiation | Iterative with bit manipulation | Recursive or iterative |
| Modular inverse | mod_pow(a, m-2, m) for prime m | Same via Fermat |
| Binomial coefficients | Precompute factorial array mod p | Same approach |
| Newtype safety | struct Mod<const M: u64>(u64) | type modint = int (no enforcement) |
OCaml Approach
OCaml's int is 63-bit on 64-bit systems, allowing products up to about 4.6 * 10^18. For moduli up to 2^30, a * b mod m stays in bounds. For larger moduli, OCaml uses Int64 or Zarith. Modular exponentiation is a clean tail-recursive function: let rec pow_mod base exp m = if exp = 0 then 1 else let half = pow_mod (base * base mod m) (exp / 2) m in if exp mod 2 = 0 then half else half * base mod m. OCaml's Fun.protect ensures cleanup in modular operations with side effects.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Modular Arithmetic
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.
Exercises
ModInt<const M: u64> newtype that overloads arithmetic operators to auto-apply modular reduction.(A * B) % m = ((A % m) * (B % m)) % m.u64 vs. u128 intermediate for modular multiplication and measure the throughput difference.