From 288c0f8c3e0a47700294ed20a3b9a03b4a5c9db3 Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 20:36:43 +0000 Subject: [PATCH] ocaml: phase 5.1 euler9.ml baseline (Project Euler #9, abc = 31875000) Find the unique Pythagorean triple with a + b + c = 1000 and return their product. The naive triple loop timed out under host contention (10-minute cap exceeded with ~333 * 999 ~= 333k inner iterations of complex checks). Rewritten with algebraic reduction: a + b + c = 1000 AND a^2 + b^2 = c^2 => b = (500000 - 1000 * a) / (1000 - a) so only the outer a-loop is needed (333 iterations). Single-pass form: for a = 1 to 333 do let num = 500000 - 1000 * a in let den = 1000 - a in if num mod den = 0 then begin let b = num / den in if b > a then let c = 1000 - a - b in if c > b then result := a * b * c end done Triple (200, 375, 425), product 31875000. 103 baseline programs total. --- lib/ocaml/baseline/euler9.ml | 17 +++++++++++++++++ lib/ocaml/baseline/expected.json | 1 + plans/ocaml-on-sx.md | 6 ++++++ 3 files changed, 24 insertions(+) create mode 100644 lib/ocaml/baseline/euler9.ml diff --git a/lib/ocaml/baseline/euler9.ml b/lib/ocaml/baseline/euler9.ml new file mode 100644 index 00000000..f687278a --- /dev/null +++ b/lib/ocaml/baseline/euler9.ml @@ -0,0 +1,17 @@ +let euler9 () = + let result = ref 0 in + for a = 1 to 333 do + let num = 500000 - 1000 * a in + let den = 1000 - a in + if num mod den = 0 then begin + let b = num / den in + if b > a then + let c = 1000 - a - b in + if c > b then result := a * b * c + end + done; + !result + +;; + +euler9 () diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 5285bebd..ba6a4e27 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -27,6 +27,7 @@ "euler1.ml": 233168, "euler2.ml": 4613732, "euler6.ml": 25164150, + "euler9.ml": 31875000, "expr_eval.ml": 16, "expr_simp.ml": 22, "factorial.ml": 3628800, diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 253e4b2b..bdc7788c 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,12 @@ _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 — euler9.ml baseline (Project Euler #9, abc + product for the unique Pythagorean triple with a+b+c=1000 → + 31875000). Naive triple loop times out under contention (10-min + cap); rewritten with algebraic reduction + `b = (500000 - 1000a) / (1000 - a)` so only one loop is needed. + Triple is (200, 375, 425). 103 baseline programs total. - 2026-05-09 Phase 5.1 — euler6.ml baseline (Project Euler #6, square of sum minus sum of squares for 1..100 = 25164150). Single for-loop threading two refs; (sum 1..100)^2 - sum(i^2 for 1..100) = 5050^2