Problem #6 Difficulty: 5%

Sum Square Difference

Solution Language: Java

The problem

For the numbers 1 to 100, take the square of their sum and subtract the sum of their squares.

My solution

The sum of squares is a plain loop, while the square of the sum uses the closed form (n(n+1)/2)², written as (100·101)²/4:

for(int i = 1; i <= 100; i++)
  a += i*i;

b = (100*101)*(100*101)/4;
c = b-a;

Everything fits comfortably in an int (10100² is about 10⁸), so overflow isn’t a concern.

Notes

The sum of squares has a closed form too, n(n+1)(2n+1)/6, so both halves can be written as formulas.