Euler's Totient Function
Tutorial Video
Text description (accessibility)
This video demonstrates the "Euler's Totient Function" functional Rust example. Difficulty level: Fundamental. Key concepts covered: Functional Programming. Euler's totient function phi(n) counts the integers from 1 to n that are coprime to n. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Euler's totient function phi(n) counts the integers from 1 to n that are coprime to n. It is fundamental to RSA key generation: the private key d satisfies e * d ≡ 1 (mod phi(n)) where n = p*q. By Euler's theorem, a^phi(n) ≡ 1 (mod n) for any a coprime to n, generalizing Fermat's little theorem. phi(n) also counts primitive roots, answers "how many fractions in lowest terms have denominator n," and appears in the analysis of the Stern-Brocot tree. For prime p, phi(p) = p-1; for prime power p^k, phi(p^k) = p^k - p^(k-1); these combine multiplicatively for general n.
🎯 Learning Outcomes
Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Per-n computation | Trial division O(sqrt n) | Same approach |
| Batch 1..n | Sieve with Vec<u64> | Array.init + sieve loop |
| Factor application | result -= result / d | r := !r - !r / d |
| Multiplicativity | Explicit in algorithm | Same |
| Standard library | No built-in | No built-in |
| RSA integration | Used in key generation tests | Same theoretical role |
OCaml Approach
OCaml's euler_totient n mirrors the Rust approach using mutable let r = ref n and let n = ref n. The sieve version initializes phi.(i) = i and iterates: for each i, if phi.(i) = i (i is prime), for each multiple j: phi.(j) <- phi.(j) / i * (i-1). OCaml's Array.init n (fun i -> i) creates the initial array. The product formula phi.(n) = n * fold primes (fun acc p -> acc * (p-1) / p) is idiomatic in functional style.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Euler Totient
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.