(*
 * Calculate the digital root of a number: add up all of its digits, and do that
 * recursively until a single digit is obtained.
 *)

let rec digitRoot ?(sum=0) number =
    let res = match number with
    | _ when number < 10 -> (sum + number)
    | _ -> (digitRoot ~sum:(sum + (number mod 10)) (number / 10))
    in if res < 10 then res else digitRoot res
;;

let test_digitRoot input =
    print_string "--- test_digitRoot ---\n";
    Printf.printf "%d -> %d\n" input (digitRoot input)
;;

test_digitRoot 20;;
test_digitRoot 24;;
test_digitRoot 1234;; (* = 1 *)
test_digitRoot 65536;; (* = 7 *)
test_digitRoot 12345678;; (* = 9 *)
test_digitRoot 18273645;; (* = 9 *)
test_digitRoot 123456789;; (* = 9 *)
test_digitRoot 1234567890123456789;; (* = 9 *)
test_digitRoot 999999999998;; (* = 8 *)
test_digitRoot 5674;; (* = 4 *)
