Blog Archives

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;
}