Project Euler in F#: Problem 16

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.

module Problem16 =
let originalSumOfDigits n =
let rec loop m acc =
if m = 0I then acc
else loop (m/10I) (acc + (m%10I))
loop n 0I

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

let ans = 2I**1000 |> sumOfDigits

Advertisements
Project Euler in F#: Problem 16

2 thoughts on “Project Euler in F#: Problem 16

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