Prime Factorization
Tutorial Video
Text description (accessibility)
This video demonstrates the "Prime Factorization" functional Rust example. Difficulty level: Intermediate. Key concepts covered: Functional Programming. Decomposing an integer into its prime factors is fundamental to number theory: computing GCD, LCM, Euler's totient, cryptographic key generation, and combinatorial coefficient calculations all rely on factorization. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Decomposing an integer into its prime factors is fundamental to number theory: computing GCD, LCM, Euler's totient, cryptographic key generation, and combinatorial coefficient calculations all rely on factorization. For small numbers, trial division by primes up to sqrt(n) suffices. For large numbers (64-bit), Pollard's rho algorithm factorizes in O(n^(1/4)) expected time. Real-world cryptography relies on the hardness of factorizing large composites (RSA). Competitive programming uses factorization for: divisor enumeration, Mobius function, Euler's phi, and modular arithmetic.
🎯 Learning Outcomes
HashMap<u64, u32>Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Factor map | HashMap<u64, u32> | Hashtbl or (int * int) list |
| Mutation | Takes mut n: u64 by value | let n = ref n |
| Entry update | .entry().or_insert(0) += 1 | Hashtbl.replace or match |
| Large numbers | u64 (max ~1.8 * 10^19) | Zarith for arbitrary precision |
| Sieve integration | Can import SPF sieve function | Array.get spf n |
| Remaining prime | if n > 1 check after loop | Same pattern |
OCaml Approach
OCaml uses a Hashtbl or returns a sorted (int * int) list of (prime, exponent) pairs. The recursive functional version divides out factors recursively, building the list with pattern matching. Trial division uses a while loop with mutable n ref. OCaml's Map.Make(Int) provides an immutable sorted factor map. The let () = while !n mod d = 0 do ... done pattern mirrors the Rust approach. For large numbers, OCaml's Zarith library handles arbitrary-precision factorization.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Prime Factorization
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.