Chinese Remainder Theorem
Tutorial Video
Text description (accessibility)
This video demonstrates the "Chinese Remainder Theorem" functional Rust example. Difficulty level: Fundamental. Key concepts covered: Functional Programming. The Chinese Remainder Theorem (CRT) solves systems of simultaneous congruences: given `x ≡ a1 (mod m1)`, `x ≡ a2 (mod m2)`, ..., find x mod (m1 * m2 * ...) when the moduli are pairwise coprime. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
The Chinese Remainder Theorem (CRT) solves systems of simultaneous congruences: given x ≡ a1 (mod m1), x ≡ a2 (mod m2), ..., find x mod (m1 m2 ...) when the moduli are pairwise coprime. This has applications in: cryptography (RSA-CRT speedup), number theory, calendar calculations, and distributed hashing. CRT also enables working with multiple small moduli instead of one large modulus, which is the key technique in Number Theoretic Transform (NTT) for polynomial multiplication. In competitive programming, CRT reconstructs a number from its remainders under several moduli, enabling range queries on large integers.
🎯 Learning Outcomes
x ≡ ai (mod mi) with pairwise coprime mi has unique solution mod M = m1m2...*mkyi = Mi^(-1) mod mi via extended GCDx = sum(ai * Mi * yi) mod MCode Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Modular inverse | Extended GCD returning Option<i64> | Returns (int * int * int) |
| Accumulation | zip iterator loop | List.fold_left2 |
| Overflow | i128 for large product M | Zarith for arbitrary precision |
| Error handling | ? operator for None propagation | Option.bind chain |
| Non-negative result | ((x % m) + m) % m | Same idiom |
| Return type | Option<i64> | int option |
OCaml Approach
OCaml's CRT uses List.fold_left to accumulate the sum: List.fold_left2 (fun acc a mi -> ...) 0 remainders moduli. The modular inverse uses the extended Euclidean algorithm returning int * int. OCaml's Int64 or Zarith handles large products. The Option type signals failure when moduli are not coprime. OCaml's pattern matching on the extended GCD result tuple is clean: let (g, x, _) = extended_gcd mi m_i in if g <> 1 then None else Some x.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Chinese Remainder Theorem
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.