Sunday, October 31, 2010

Problem: Euler Task 6 - Difference between Square of Sums and Sum of Squares

Well, task no 6 is pretty straight forward, so I write the solution quickly. Promise. I will stop coding this evening even when it is still raining  out there.

The problem is the following:

"The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 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."


First let's define square function. Easy:

def square(x : Int) = x * x

We define then the diff method that calculate the difference. The function receives a Range as its input. It is defined as follow:

def diff(r: Range) = 
   square( r.foldLeft(0)(_ + _)) - r.foldLeft(0)(_ + square(_))


The answer to the problem is then diff( 1 to 100).

While the exercise is easy, this is kind of problem where Scala, or functional programming in general, at its best: only three lines to solve this problem (I can even tweet the solution). That's why I find this exercise quite interesting.





1 comment:

Flat Roofing Contractors Vancouver said...

I really enjoyed your blog posts, thank you