Skip to content

Project Euler Problem 34

November 22, 2011

I begin Project Euler Problem 34 solution with finding what would be the upper limit for sum of digit factorials, considering that max such sum for a fixed number of digits would be for number consisting of all 9s.

From here the rest of the solution is straightforward: check all numbers between 10 and this upper bound, filtering in those having the sought property; and complete with finding their sum.

let digitFact  = function
    | 0 | 1 -> 1
    | 2 -> 2
    | 3 -> 6
    | 4 -> 24
    | 5 -> 120
    | 6 -> 720
    | 7 -> 5040
    | 8 -> 40320
    | 9 -> 362880
    | _ -> failwith "bad argument"


let maxAsSumOfDigitsFact =
    let nineFact = digitFact 9
    let rec maxN (n: int) =
        if  pown 10 n > nineFact * n then
            nineFact * n
        else
            maxN (n + 1)
    maxN 2

let asSumOfDigitsFact (n: int) =
    Seq.unfold (fun x ->
        if x = 0 then None else Some(digitFact (x%10), x/10) ) n
    |> Seq.sum
    
let problem034 () =
    [10..maxAsSumOfDigitsFact]
    |> List.filter (fun x -> x = asSumOfDigitsFact x)
    |> List.sum
Advertisements

From → Project Euler

One Comment

Trackbacks & Pingbacks

  1. Project Euler Problem 74 « In F# Major

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: