Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Sum Square Difference

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.

Solution

It’s a pretty straightforward problem. We can simply write down the problem literally, without any optimizations, and we’re good to go. Scala’s expressiveness makes this task a breeze and the resulting code is easy to understand.

To make it extra concise, let’s also define a “square” extension method.

object Euler006 extends EulerApp {
  override def execute(): Int = squareOfSums(100) - sumOfSquares(100)

  private def sumOfSquares(n: Int) = (1 to n).map(_.square).sum

  private def squareOfSums(n: Int) = (1 to n).sum.square

  extension (i: Int) {
    def square: Int = i * i
  }
}