Zachary Stence

Problem 6: Sum square difference

The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 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.

I first solved this problem October 8th, 2014 in my AP Computer Science class in highschool. I do not have the original code I wrote, but I have redone the solution and included it below.

This problem is perhaps the easiest one yet on ProjectEuler. I just wrote two functions that return the sum of the squares and the square of the sum of the first n natural numbers (sumOfSq and sqOfSum, respectively). Then I just called them with 100 as the argument, and output the difference.

#include <iostream>

int sumOfSq(int n) {
  int sum = 0;
  for (int i = 1; i <= n; i++) {
    sum += i * i;
  }
  return sum;
}

int sqOfSum(int n) {
  int sum = 0;
  for (int i = 1; i <= n; i++) {
    sum += i;
  }
  return sum * sum;
}

int main() {
  std::cout << sqOfSum(100) - sumOfSq(100) << std::endl;
}

Answer: 25164150