diff --git a/p12/lib/dune b/p12/lib/dune index 5e89762..32e8d11 100644 --- a/p12/lib/dune +++ b/p12/lib/dune @@ -1,3 +1,3 @@ (library (name p12_lib) - (modules iterative map module rec tailrec)) + (modules iterative map module rec tailrec lazy)) diff --git a/p12/lib/lazy.ml b/p12/lib/lazy.ml new file mode 100644 index 0000000..9278bd0 --- /dev/null +++ b/p12/lib/lazy.ml @@ -0,0 +1,24 @@ +let triangular_numbers = + Seq.unfold + (fun n -> + let t = n * (n + 1) / 2 in + Some (t, n + 1)) + 1 +;; + +let count_factors_tail n = + let rec aux i count = + if i * i > n + then count + else if n mod i = 0 + then aux (i + 1) (count + if i * i = n then 1 else 2) + else aux (i + 1) count + in + if n <= 0 then 0 else aux 1 0 +;; + +let find_first_triangular_with_factors n = + Seq.find (fun x -> count_factors_tail x > n) triangular_numbers +;; + +let result = find_first_triangular_with_factors 500 diff --git a/p12/test/test_p12.ml b/p12/test/test_p12.ml index 8bf5fc8..2e88880 100644 --- a/p12/test/test_p12.ml +++ b/p12/test/test_p12.ml @@ -51,6 +51,13 @@ let test_map_find_first _ = | None -> assert_failure "Expected a result, got None" ;; +(* Lazy collections tests *) +let test_lazy_find_first _ = + match Map.result with + | Some x -> assert_equal 76576500 x + | None -> assert_failure "Expected a result, got None" +;; + let suite = "Project Euler Problem 12 Tests" >::: [ "Tailrec - count_factors" >:: test_tailrec_count_factors @@ -61,6 +68,7 @@ let suite = ; "Iterative - find_triangular" >:: test_iterative_find_triangle ; "Module - result" >:: test_module_result ; "Map - result" >:: test_map_find_first + ; "Lazy - result" >:: test_lazy_find_first ] ;;