Project Euler – Problem 20 Solution

Yan Cui

I help clients go faster for less using serverless technologies.

Problem

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

Find the sum of the digits in the number 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 solution is pretty straight forward, though you might be curious as to what the rec keyword in the factorial function is for. In F# you need to explicitly specify that a function can be recursive and you do so with the rec keyword.

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 function is basically Seq.map and Seq.sum functions rolled into one.


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


2 thoughts on “Project Euler – Problem 20 Solution”

  1. Pingback: 10 one-line solutions for project euler | united-coders.com

  2. Pingback: united-coders - 10 one-line solutions for project euler

Leave a Comment

Your email address will not be published. Required fields are marked *