let pow_digit_sum n p =
  let m = ref n in
  let s = ref 0 in
  while !m > 0 do
    let d = !m mod 10 in
    let pd = ref 1 in
    for _ = 1 to p do pd := !pd * d done;
    s := !s + !pd;
    m := !m / 10
  done;
  !s

let euler30 p limit =
  let total = ref 0 in
  for n = 2 to limit do
    if pow_digit_sum n p = n then total := !total + n
  done;
  !total

;;

euler30 3 999
