The sum of the squares of the first ten natural numbers is,
The square of the sum of the first ten natural numbers is,
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 — 385 = 3640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
This problem is quite straight forward so I turned to Linq and used some obvious brute force:
var answer = numbers.Sum() * numbers.Sum() - numbers.Aggregate(0, (sum, n) => sum + n * n);
This gives the answer, in 0 ms, around 2-3000 ticks.
However, my brother went further and found some pretty smart optimizations. Had to have a look at those of course and see if I could make sense of those too. It all boils down to expansion of power summations.
The Euler problem we are trying to solve here can be described mathematically like this:
In other words, the answer can be found very easily if we have the formulas for m=1 and m=2. And that we do:
Turning those into two C# methods is quite easy and we can find our answer like so:
return (n * n + n) / 2;
static ulong SumExpansion2(ulong n)
return n * (n + 1) * (2 * n + 1) / 6;
var answer = SumExpansion1(100) * SumExpansion1(100) - Numbers.SumExpansion2(100);
That also takes 0 ms, but we are down to around 2-300 ticks. So, compared to the brute force solution, this only takes 10% of the time. Awesome ^_^
The formula can actually be simplified a bit if we bring out our math skills. Not that my math skills really deserve being called skills, but anyways 😛
Now, our answer can be found like this:
var answer = (3*n*n*n*n + 2*n*n*n - 3*n*n - 2*n) / 12;
Which, compared to take 2, takes about half the time. Around 150 ticks. 8)
Alright… done with this one now…