Euler #6 : Squares and Sums
by Nicolas Wu
Posted on 5 August 2010
This week’s Project Euler puzzle is extremely simple compared to the ones we’ve had so far:
What is the difference between the sum of the squares and the square of the sums?
We start this answer by defining
square, which is simply the function that squares its argument:
Our answer falls out quite directly, and the question asks for the value of the difference between the sum of the squares and the square of the sums of the numbers between
Here we’ve used the function
abs that returns the absolute (positive) value of a number:
Strictly speaking, we didn’t need to use this since the values returned are always positive, but it’s a useful function worth knowing. Even more useful is the function
($), which we’ve put just after
abs. This function applies its left argument to the expression to its right. Here’s its type:
This operator is given the least precedence when working out how it binds, which basically makes it useful for avoiding large parenthesised expressions. You should think of it as wrapping brackets around its right argument as far as it can.
There really isn’t much to summarize this time, except for squares of lists … oh, and:
($)operator is useful for avoiding lots of brackets.