What is the sum of the digits of the number 21000?
module Problem16 = let sumOfDigits n = let rec loop m acc = if m = 0I then acc else loop (m/10I) (acc + (m%10I)) loop n 0I let ans = 2I**1000 |> sumOfDigits
The naive solution works well enough, but when IntelliSense revealed that bigint has a DivRem method, I had to try that.
let rec sumOfDigits n = let rec loop m acc = if m = 0I then acc else let div,rem = bigint.DivRem (m,10I) loop div (acc + rem) loop n 0I
It’s twice as fast as the original solution, but a bit messier. This seems like the kind of thing that could be done automatically by a compiler optimization.