Files
rose-ash/lib/ocaml/baseline/euler36.ml
giles ed8aaf8af7
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
ocaml: phase 5.1 euler36.ml baseline (sum of double-base palindromes <= 1000 = 1772)
Numbers that read the same in base 10 and base 2:

  1, 3, 5, 7, 9, 33, 99, 313, 585, 717
  sum = 1772

Implementation:
  pal_dec n        check decimal palindrome via index walk
  to_binary n      build binary string via mod 2 / div 2 stack
  pal_bin n        check binary palindrome
  euler36 limit    scan 1..limit-1, sum where both palindromes

Real PE36 uses 10^6 (answer 872187). 1000 takes ~9 minutes on
contended host but stays within reasonable budget for the
spec-level evaluator.

123 baseline programs total.
2026-05-10 00:26:46 +00:00

42 lines
838 B
OCaml

let pal_dec n =
let s = string_of_int n in
let len = String.length s in
let p = ref true in
for i = 0 to len / 2 - 1 do
if s.[i] <> s.[len - 1 - i] then p := false
done;
!p
let to_binary n =
if n = 0 then "0"
else
let buf = Buffer.create 32 in
let m = ref n in
let stack = ref [] in
while !m > 0 do
stack := (!m mod 2) :: !stack;
m := !m / 2
done;
List.iter (fun d -> Buffer.add_string buf (string_of_int d)) !stack;
Buffer.contents buf
let pal_bin n =
let s = to_binary n in
let len = String.length s in
let p = ref true in
for i = 0 to len / 2 - 1 do
if s.[i] <> s.[len - 1 - i] then p := false
done;
!p
let euler36 limit =
let sum = ref 0 in
for n = 1 to limit - 1 do
if pal_dec n && pal_bin n then sum := !sum + n
done;
!sum
;;
euler36 1000