Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 37s
Build the Champernowne string '12345678910111213...' until at
least 1500 chars; product of digits at positions 1, 10, 100, 1000
is 1 * 1 * 5 * 3 = 15.
Initial implementation timed out: 'String.length (Buffer.contents
buf) < 1500' rebuilt the full string each iteration (O(n^2) in our
spec-level evaluator). Fixed by tracking length separately from
the Buffer:
let len = ref 0 in
while !len < 1500 do
let s = string_of_int !i in
Buffer.add_string buf s;
len := !len + String.length s;
i := !i + 1
done
Real PE40 uses positions up to 10^6 (answer 210); 1000 keeps under
budget while exercising the same string-build + char-pick pattern.
122 baseline programs total.
23 lines
465 B
OCaml
23 lines
465 B
OCaml
let euler40 () =
|
|
let buf = Buffer.create 4096 in
|
|
let len = ref 0 in
|
|
let i = ref 1 in
|
|
while !len < 1500 do
|
|
let s = string_of_int !i in
|
|
Buffer.add_string buf s;
|
|
len := !len + String.length s;
|
|
i := !i + 1
|
|
done;
|
|
let s = Buffer.contents buf in
|
|
let prod = ref 1 in
|
|
let positions = [1; 10; 100; 1000] in
|
|
List.iter (fun p ->
|
|
let c = s.[p - 1] in
|
|
prod := !prod * (Char.code c - Char.code '0')
|
|
) positions;
|
|
!prod
|
|
|
|
;;
|
|
|
|
euler40 ()
|