Skip to content

Instantly share code, notes, and snippets.

@l0gicpath
Created February 22, 2014 04:39
Show Gist options
  • Save l0gicpath/9148851 to your computer and use it in GitHub Desktop.
Save l0gicpath/9148851 to your computer and use it in GitHub Desktop.
Euler problem #53 in OCaml
(* taking out the big guns, yes... size matters *)
open Num
open Printf
(* a throw away helper function just like pred but works with Nums, ought to give it a better name *)
let pred' n = Int (pred (int_of_num n))
(* field test *)
let rec fact x = if x =/ Int 0 then Int 1 else x */ fact (pred' x)
(* our weapon *)
let c n r =
if r <= n then
let n' = fact (Int n) in
let r' = fact (Int r) in
n' // (r' */ fact (Int n -/ Int r))
else
raise (Failure "r > n")
(* our hero *)
let count_combinatorics =
let r = ref 100 in
let rec count_combinatorics' n count =
match n with
| 22 -> count
| _ ->
match !r with
| 2 ->
let combinatorics = c n !r in (
r := (pred n);
if combinatorics >/ Int 1_000_000 then count_combinatorics' (pred n) (succ count)
else count_combinatorics' (pred n) count
)
| _ ->
let combinatorics = c n !r in (
r := pred !r;
if combinatorics >/ Int 1_000_000 then count_combinatorics' n (succ count)
else count_combinatorics' n count
)
in
count_combinatorics' 100 0
(* le hero's boss *)
let () = printf "Count of values above 1m = %d\n" count_combinatorics
(*
* Compile it
* $ ocamlbuild -libs nums euler53.native && mv euler53.native euler53
* Then run it
* $ ./euler53
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment