From af38d98583277f7234b6cd27fa88202fb17026a6 Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 12:44:02 +0000 Subject: [PATCH] ocaml: phase 5.1 prime_factors.ml baseline (trial-division, 360 factor sum = 17) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three refs threading through a while loop: m remaining quotient d current divisor result accumulator (built in reverse, List.rev at end) while !m > 1 do if !m mod !d = 0 then begin result := !d :: !result; m := !m / !d end else d := !d + 1 done 360 = 2^3 * 3^2 * 5 factors to [2;2;2;3;3;5], sum 17. 60 baseline programs total — milestone. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/prime_factors.ml | 16 ++++++++++++++++ plans/ocaml-on-sx.md | 6 ++++++ 3 files changed, 23 insertions(+) create mode 100644 lib/ocaml/baseline/prime_factors.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 1db31844..12d1d880 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -46,6 +46,7 @@ "pi_leibniz.ml": 314, "pretty_table.ml": 64, "poly_stack.ml": 5, + "prime_factors.ml": 17, "queens.ml": 2, "quicksort.ml": 44, "roman.ml": 44, diff --git a/lib/ocaml/baseline/prime_factors.ml b/lib/ocaml/baseline/prime_factors.ml new file mode 100644 index 00000000..382f0e8b --- /dev/null +++ b/lib/ocaml/baseline/prime_factors.ml @@ -0,0 +1,16 @@ +let factor n = + let result = ref [] in + let m = ref n in + let d = ref 2 in + while !m > 1 do + if !m mod !d = 0 then begin + result := !d :: !result; + m := !m / !d + end else + d := !d + 1 + done; + List.rev !result + +;; + +List.fold_left (+) 0 (factor 360) diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index accd5f67..1cd88fe1 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 — prime_factors.ml baseline (trial-division + factorisation, sum of factors of 360 = 17). Three refs threading + through a while loop: m holds the remaining quotient, d the + current divisor, result accumulates factors. When `m mod d = 0`, + push d and divide; otherwise increment d. 360 = 2^3 * 3^2 * 5 + factors to [2;2;2;3;3;5], sum 17. 60 baseline programs total. - 2026-05-09 Phase 5.1 — atm.ml baseline (mutable record + custom exception + try/with, balance 120 after rollback). Models a bank account: deposit/withdraw mutate the balance field; an over-draw