Files
rose-ash/lib/ocaml/baseline/euler21_small.ml
giles 87f9a84365
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
ocaml: phase 5.1 euler21_small.ml baseline (sum of amicable numbers <= 300 = 504)
div_sum computes proper divisor sum via trial division up to sqrt(n):

  let div_sum n =
    let s = ref 1 in
    let i = ref 2 in
    while !i * !i <= n do
      if n mod !i = 0 then begin
        s := !s + !i;
        let q = n / !i in
        if q <> !i then s := !s + q
      end;
      i := !i + 1
    done;
    if n = 1 then 0 else !s

Outer loop finds amicable pairs (a, b) with d(a) = b, d(b) = a,
a != b. Only pair under 300 is (220, 284); 220 + 284 = 504.

Real PE21 uses 10000 (answer 31626). 300 keeps the run under
budget while exercising the same divisor-sum trick.

119 baseline programs total.
2026-05-09 23:27:15 +00:00

26 lines
462 B
OCaml

let div_sum n =
let s = ref 1 in
let i = ref 2 in
while !i * !i <= n do
if n mod !i = 0 then begin
s := !s + !i;
let q = n / !i in
if q <> !i then s := !s + q
end;
i := !i + 1
done;
if n = 1 then 0 else !s
let euler21 limit =
let total = ref 0 in
for a = 2 to limit do
let b = div_sum a in
if b <> a && b > a && b <= limit && div_sum b = a then
total := !total + a + b
done;
!total
;;
euler21 300