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 3 ways I can help you:
- Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
- I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.
Pingback: 10 one-line solutions for project euler | united-coders.com
Pingback: united-coders - 10 one-line solutions for project euler