let fact n =
  let r = ref 1 in
  for i = 2 to n do r := !r * i done;
  !r

let digit_fact_sum n =
  let m = ref n in
  let s = ref 0 in
  while !m > 0 do
    s := !s + fact (!m mod 10);
    m := !m / 10
  done;
  !s

let euler34 limit =
  let total = ref 0 in
  for n = 3 to limit do
    if digit_fact_sum n = n then total := !total + n
  done;
  !total

;;

euler34 2000
