Project Euler — Problem 20 Solution

Problem

n! means n x (n — 1) x … x 3 x 2 x 1

Find the sum of the dig­its in the num­ber 100!

Solution

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

let number = factorial 100I
let digits = number.ToString().ToCharArray() |> Seq.map (fun c -> int32(c.ToString()))
let sum = digits |> Seq.sum

This solu­tion is pret­ty straight for­ward, though you might be curi­ous as to what the rec key­word in the fac­to­r­i­al func­tion is for. In F# you need to explic­it­ly spec­i­fy that a func­tion can be recur­sive and you do so with the rec key­word.

Note that the last three lines can be merged into one:

let answer = (factorial 100I).ToString().ToCharArray() |> Seq.sumBy (fun c -> int32(c.ToString()))

The Seq.sumBy func­tion is basi­cal­ly Seq.map and Seq.sum func­tions rolled into one.