Published at Oct 17 2019
·
0 comments

Instructions

Test suite

Solution

Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.

The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)² = 55² = 3025.

The sum of the squares of the first ten natural numbers is 1² + 2² + ... + 10² = 385.

Hence the difference between the square of the sum of the first ten natural numbers and the sum of the squares of the first ten natural numbers is 3025 - 385 = 2640.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test`

in the exercise directory.

For more detailed info about the Scala track see the help page.

Problem 6 at Project Euler http://projecteuler.net/problem=6

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
import org.scalatest.{Matchers, FunSuite}
/** @version 1.2.0 */
class DifferenceOfSquaresTest extends FunSuite with Matchers {
test("square of sum 1") {
DifferenceOfSquares.squareOfSum(1) should be (1)
}
test("square of sum 5") {
pending
DifferenceOfSquares.squareOfSum(5) should be (225)
}
test("square of sum 100") {
pending
DifferenceOfSquares.squareOfSum(100) should be (25502500)
}
test("sum of squares 1") {
pending
DifferenceOfSquares.sumOfSquares(1) should be (1)
}
test("sum of squares 5") {
pending
DifferenceOfSquares.sumOfSquares(5) should be (55)
}
test("sum of squares 100") {
pending
DifferenceOfSquares.sumOfSquares(100) should be (338350)
}
test("difference of squares 1") {
pending
DifferenceOfSquares.differenceOfSquares(1) should be (0)
}
test("difference of squares 5") {
pending
DifferenceOfSquares.differenceOfSquares(5) should be (170)
}
test("difference of squares 100") {
pending
DifferenceOfSquares.differenceOfSquares(100) should be (25164150)
}
}
```

```
object DifferenceOfSquares {
def sumOfSquares(n: Int): Int = {
val squares =
for {
i <- 1 to n
} yield (i*i)
squares.sum
}
def squareOfSum(n: Int): Int = {
val numSum = (1 to n).sum
numSum*numSum
}
def differenceOfSquares(n: Int): Int = {
squareOfSum(n) - sumOfSquares(n)
}
}
```

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that you could read more about to improve your understanding?

Level up your programming skills with 3,092 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments