The problem is the following:

*"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."*

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.

## No comments:

Post a Comment