Tags

, , ,

From ProjectEuler.net:

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.

C++ SolutionI’m just going to say it: I really don’t get why this one is even here. It has to be the easiest of all the first six problems. I usually feel like each ProjectEuler problem is cleverly designed to teach some new concept or syntax, or reveal a flaw in earlier code – but I don’t see it with this one.

Anyhoo, I used just a single loop, in which I summed all the squares, and also kept track of the sum. After that, I just squared the sum, subtracted, and there you are.

Project Euler #6 Solution

C++ Output

 

C++ code:

#include <iostream>

using namespace std;

int main()
{
    long sumOfSquares = 0;
    long sum = 0;
    long squareOfSums = 0;

    for (int i = 1; i < 101; i++){sumOfSquares += i*i; sum += i;}
    squareOfSums = sum*sum;
    cout << endl << "The difference between the sum of the squares and the square of the sums of the first 100 natural numbers is: " << abs(squareOfSums-sumOfSquares) << "." << endl;
    return 0;
}

Python:

import math

sumOfSquares = 0
sumz = 0
squareOfSumz = 0

for i in range(1, 101):
    sumOfSquares += i*i
    sumz += i

print "The difference between the sum of the squares and the square of the sums of the first 100 natural numbers is: " + str(abs(sumOfSquares-(sumz*sumz))) + "."
Advertisements