From 30b237a8914d72a72f384499579c2cea94ac045b Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 15:11:46 +0000 Subject: [PATCH] ocaml: phase 5.1 mod_inverse.ml baseline (extended Euclidean, inverse sum = 27) Extended Euclidean returns a triple (gcd, x, y) such that a*x + b*y = gcd: let rec ext_gcd a b = if b = 0 then (a, 1, 0) else let (g, x1, y1) = ext_gcd b (a mod b) in (g, y1, x1 - (a / b) * y1) let mod_inverse a m = let (_, x, _) = ext_gcd a m in ((x mod m) + m) mod m Three invariants checked: inv(3, 11) = 4 (3*4 = 12 = 1 mod 11) inv(5, 26) = 21 (5*21 = 105 = 1 mod 26) inv(7, 13) = 2 (7*2 = 14 = 1 mod 13) sum = 27 Tests recursive triple-tuple return, tuple-pattern destructuring on let-binding (with wildcard for unused fields), and nested let-binding inside the recursive call site. 72 baseline programs total. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/mod_inverse.ml | 13 +++++++++++++ plans/ocaml-on-sx.md | 9 +++++++++ 3 files changed, 23 insertions(+) create mode 100644 lib/ocaml/baseline/mod_inverse.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index c158e019..6a323ea1 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -36,6 +36,7 @@ "flatten_tree.ml": 28, "list_ops.ml": 30, "mat_mul.ml": 621, + "mod_inverse.ml": 27, "json_pretty.ml": 24, "kadane.ml": 6, "lambda_calc.ml": 7, diff --git a/lib/ocaml/baseline/mod_inverse.ml b/lib/ocaml/baseline/mod_inverse.ml new file mode 100644 index 00000000..6f5c7579 --- /dev/null +++ b/lib/ocaml/baseline/mod_inverse.ml @@ -0,0 +1,13 @@ +let rec ext_gcd a b = + if b = 0 then (a, 1, 0) + else + let (g, x1, y1) = ext_gcd b (a mod b) in + (g, y1, x1 - (a / b) * y1) + +let mod_inverse a m = + let (_, x, _) = ext_gcd a m in + ((x mod m) + m) mod m + +;; + +mod_inverse 3 11 + mod_inverse 5 26 + mod_inverse 7 13 diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 6d6a3f86..3398aab6 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,15 @@ _Newest first._ binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree`) with insert + in-order traversal. Tests parametric ADT, recursive match, List.append, List.fold_left. +- 2026-05-09 Phase 5.1 — mod_inverse.ml baseline (extended Euclidean + + modular inverse, sum 4+21+2 = 27). ext_gcd returns a triple + (gcd, x, y) such that ax + by = gcd. mod_inverse extracts x and + reduces mod m to a positive representative. Three checks: + inv(3, 11) = 4 (3*4 = 12 ≡ 1) + inv(5, 26) = 21 (5*21 = 105 ≡ 1) + inv(7, 13) = 2 (7*2 = 14 ≡ 1) + Sum = 27. Tests recursive triple-tuple return + tuple-pattern + destructuring + nested let-binding. 72 baseline programs total. - 2026-05-09 Phase 5.1 — hist.ml baseline (Hashtbl-based int histogram, total * max = 75). Three small functions: hist builds the count table, max_value finds the maximum bin, total sums all