Files
rose-ash/lib/ocaml/baseline/is_prime.ml
giles c16a8f2d53
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
ocaml: phase 5.1 is_prime.ml baseline (count primes <= 100 = 25)
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.
2026-05-09 21:16:40 +00:00

22 lines
328 B
OCaml

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