Avatar of Ric0chet

Ric0chet's solution

to Difference Of Squares in the Scala Track

Published at Sep 23 2019 · 1 comment
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)
  }
}
//  09-23-19

// 43 ms
object DifferenceOfSquares {
  // sum(n)^2 - sum(n^2)
  def differenceOfSquares(n: Int): Int = squareOfSum(n) - sumOfSquares(n)

  // "Triangle Numbers" -- sum(n)^2
  def squareOfSum(n: Int): Int = n * n * (n * n + 2 * n + 1) / 4

  // "Pyramidal Numbers" -- sum(n^2)
  def sumOfSquares(n: Int): Int = (n * (n + 1) * (2 * n + 1)) / 6
}

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of Ric0chet

Ric0chet's Reflection

A pure Math solution. Much faster than invoking map iterators or pow().