🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉 # SergiiVlasiuk's solution

## to Difference Of Squares in the Scala Track

Published at Aug 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.

## Source

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

## Submitting Incomplete Solutions

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

### DifferenceOfSquaresTest.scala

``````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)
}
}``````
``````import scala.math.pow

object DifferenceOfSquares {

def sumOfSquares(n: Int): Int = (1 to n).map(x => x * x).sum

def squareOfSum(n: Int): Int = pow((1 to n).sum, 2).toInt

def differenceOfSquares(n: Int): Int = squareOfSum(n) - sumOfSquares(n)
}``````