Project Euler Problem# 6 solution in C++

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.

Efficient solution without using any loops. So it will be constant time method:

#include<iostream>

using namespace std;

int main ()
{
int maxNum = 0;
int sum_of_square = 0;
int square_of_sum = 0;

cout << “Enter Maximum number: “;
cin >> maxNum;

sum_of_square = ((maxNum*(maxNum +1))*((2*maxNum)+1))/6;

square_of_sum *= square_of_sum = maxNum* (maxNum+1)/2;

cout << “sum of squares till ” << maxNum << ” is: ” << sum_of_square << endl;
cout << “squares of sum till ” << maxNum << ” is: ” << square_of_sum << endl;
cout << “difference between the sum of the squares the square of the sum: ” << square_of_sum – sum_of_square  << endl;
}

Advertisements

About Khuram Ali

Programming... Programming and Programming...!!!

Posted on April 1, 2013, in Algorithms, C++, Project Euler and tagged , , . Bookmark the permalink. 2 Comments.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: