I've created a (very) simple solution for Project Euler problem 6:
Project Euler Problem 6: Sum square difference
The sum of the squares of the first ten natural numbers is,
$$ 1^2 + 2^2 + ... + 10^2 = 385 $$
The square of the sum of the first ten natural numbers is,
$$ (1 + 2 + ... + 10)^2 = 55^2 = 3025 $$
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is \$3025 − 385 = 2640\$.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
Solution:
\$25164150\$
To solve this in F# was pretty simple: I simply declared a function square
which would multiply an x
by itself, then a function which would run through a list of numbers and add the square of the sum of them, and subtract the sum of the squares of each.
let square x =
x * x
let calcDiffSquareSumFromSumSquares list =
(list |> List.sum |> square) - (list |> List.sumBy square)
printfn "Solution to Project Euler 6: %i" (calcDiffSquareSumFromSumSquares [ 1 .. 100 ])
On this one, I'm particularly curious if there's a functional way to run through the list only once, calculate the total sum, and calculate the squares of sums so that I wouldn't need to use two sum methods.
List.fold
, which is a very functional and generic way of "merging" values into one. \$\endgroup\$