Project Euler Problem 6

December 14, 2011

I mentioned yesterday, I’ve been doing the first few problems of Project Euler and figured I’d share my solution to problem 6 here.

The Problem
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

The Solution
This one is pretty straight forward. Find a data structure capable of holding the square of the sum of numbers 1 to 100 and subtract the squares of the first 100 natural numbers.

#include 
using namespace std;

int main () {
        unsigned long sumsquares = 0, sums = 0;
        int n;

        cout <> n;

        while (n < 0) {
                cout <> n;
        }

        for(int i = 1; i <= n; i++) {
                cout << "i: " << i << endl;
                sumsquares += i * i;
                cout << "sumsquares: " << sumsquares << endl;
                sums += i;
                cout << "sums: " << sums << endl;
        }

        cout << "The sum of squares from 1 to " << n << ": " << sumsquares << endl;
        cout << "The square of sums from 1 to " << n << ": " << sums * sums << endl << endl;
        cout << "The difference: " << (sums * sums - sumsquares) << endl;

        return(0);
}

As you can see, there is a loop creating the sum and the sum of squares. From there, it subtracts the square of the sum and the sum of squares to get the answer.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive