Project Euler Problem 6

Sum Square Difference

Find the difference between the sum of the squares and the square of the sum of all the numbers from 1 to 100.

Solution

For such a small search space, we can iterate over all the numbers from 1 to 100 and keep a running total of the sum of the squares and the sum (which we square at the end).

package main

import "fmt"

func main() {
	sumSquares := 0
	squareSum := 0
	difference := 0

	for n := 1; n <= 100; n++ {
		sumSquares += n * n
		squareSum += n
	}

	squareSum *= squareSum

	if sumSquares > squareSum {
		difference = sumSquares - squareSum
	} else {
		difference = squareSum - sumSquares
	}

	fmt.Println(difference)
}

If the search space was much larger, we could optimise the sum of the numbers by pairing off the numbers and then multiplying the result. For example, the numbers 1 to 100 can be paired off as two numbers which add up to 101 (1 and 100, 2 and 99 … 50 and 51). There are 50 such pairs, so the sum of the numbers would be: 50 x 101. This should be more efficient than simply adding up the numbers, as the loop above has:

The optimised version would have:

However, on modern CPUs that can execute millions of instructions per second (especially ADD instructions, which are cheap relative to many others), it’s unlikely to be a major benefit. We would also still need the loop to exist for the sum of squares.