60 Days of Euler in F# - Problem 20

The Problem

Sum the digits in 100! (factorial of 100).

The Solution

.NET's BigInteger to the rescue. Again.

First, let's compute the factorial.

let rec factorial (n : BigInteger) =
    if (n = 1I) 
    then 1I
    else n * factorial (n - 1I)

The above is the classic, recursive implementation of the factorial function.

With that in hand, finding the answer is trivial.

(factorial 100I).ToString()
|> Seq.map (fun c -> int32(string c))
|> Seq.sum

The above converts 100! to a string, then converts that into digits and then, finally, sums those digits.

Other Posts in This Series