Miller-Rabin Primality Test
Tutorial Video
Text description (accessibility)
This video demonstrates the "Miller-Rabin Primality Test" functional Rust example. Difficulty level: Fundamental. Key concepts covered: Functional Programming. Deterministic primality testing via trial division is O(sqrt(n)), impractical for 64-bit numbers (up to 4 billion operations). Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Deterministic primality testing via trial division is O(sqrt(n)), impractical for 64-bit numbers (up to 4 billion operations). Cryptographic applications need to test numbers with hundreds of digits for primality during key generation. Miller-Rabin is a probabilistic primality test that runs in O(k log^2 n) where k is the number of witness rounds — each round reduces error probability to 1/4. With k=25 rounds, the probability of a false positive is negligible. For 64-bit integers, a specific set of deterministic witnesses {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} makes Miller-Rabin deterministic — no false positives for any n < 3.3 * 10^24.
🎯 Learning Outcomes
a^d ≠ 1 (mod n) AND a^(2^j * d) ≠ -1 (mod n) for all j means compositeCode Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| 64-bit modular mul | as u128 intermediate | Int64 or Zarith |
| Witness iteration | for &a in &[...] | List.for_all |
| Overflow safety | u128 prevents overflow | Zarith arbitrary precision |
| Deterministic range | n < 3.3 * 10^24 | Same witnesses, same range |
| False positives | None with chosen witnesses | None |
| Probabilistic mode | Add random witnesses | Random.int64 witnesses |
OCaml Approach
OCaml's Miller-Rabin decomposes n-1 using a recursive/iterative bit-strip. The witness list is a let witnesses = [2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37]. The test uses List.for_all (fun a -> not (is_composite n a d r)) witnesses. OCaml's Int64 or Zarith handles modular multiplication for large n. The 63-bit native int suffices for n < 2^62; for full 64-bit range, Int64 or Zarith.mpz is needed.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Miller Rabin Primality
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.