From c16a8f2d53bf9362609a7d80d81bacbe34c3f5f1 Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 21:16:40 +0000 Subject: [PATCH] ocaml: phase 5.1 is_prime.ml baseline (count primes <= 100 = 25) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trial division up to sqrt(n) with early-exit via bool ref: let is_prime n = if n < 2 then false else let p = ref true in let i = ref 2 in while !i * !i <= n && !p do if n mod !i = 0 then p := false; i := !i + 1 done; !p Outer count_primes loops 2..n calling is_prime, accumulating count. Returns 25 — the canonical prime-counting function pi(100). 107 baseline programs total. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/is_prime.ml | 21 +++++++++++++++++++++ plans/ocaml-on-sx.md | 6 ++++++ 3 files changed, 28 insertions(+) create mode 100644 lib/ocaml/baseline/is_prime.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 7613a491..862e864c 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -46,6 +46,7 @@ "hanoi.ml": 1023, "hist.ml": 75, "int_sqrt.ml": 1027, + "is_prime.ml": 25, "fizz_classifier.ml": 540, "fizzbuzz.ml": 57, "flatten_tree.ml": 28, diff --git a/lib/ocaml/baseline/is_prime.ml b/lib/ocaml/baseline/is_prime.ml new file mode 100644 index 00000000..8e97fb0f --- /dev/null +++ b/lib/ocaml/baseline/is_prime.ml @@ -0,0 +1,21 @@ +let is_prime n = + if n < 2 then false + else + let p = ref true in + let i = ref 2 in + while !i * !i <= n && !p do + if n mod !i = 0 then p := false; + i := !i + 1 + done; + !p + +let count_primes n = + let c = ref 0 in + for i = 2 to n do + if is_prime i then c := !c + 1 + done; + !c + +;; + +count_primes 100 diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index e9809c3a..56749bed 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 — is_prime.ml baseline (count primes ≤ 100 = + 25). Trial division up to √n with early-exit via bool ref. Loop + 2..n calling is_prime, accumulate count. Returns 25 (the canonical + prime-counting function π(100)). Tests two cooperating functions + + while-with-bool-short-circuit + nested for. 107 baseline + programs total. - 2026-05-09 Phase 5.1 — catalan.ml baseline (Catalan number C(5) via DP recurrence = 42). DP recurrence `C(n) = sum_{j=0}^{n-1} C(j) * C(n-1-j)`. C(5) = 42 — also the count of distinct binary