What is the difference between the sum of the squares and the square of the sums.

Project Euler Problem 6: 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.
Solution: The problem is quite straight forward. We have to to find two sums and then find the difference. Here is an Brute force approach for it. Enter the range as 100 in the prompt. And you are good to go.


Java implementation of above is as follows:


import java.io.*;
class DiffOfSquares{
int range;
long sumOfSq,sqOfSum;
long diffOfSq;
void findDiff(){
int i=1;
for(i = 1;i<=range;i++){
sumOfSq += i*i;
sqOfSum += i;
}
sqOfSum *=sqOfSum;
diffOfSq = sqOfSum - sumOfSq;
System.out.println("The Sq of Sum is :"+sqOfSum);
System.out.println("The Sum of sq is :"+sumOfSq);
System.out.println("The Differnce is :"+diffOfSq);
}
void setRange(){
System.out.println("Enter the range :");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try{
String str = br.readLine();
range = Integer.parseInt(str);
}
catch(IOException e){}
findDiff();
}
}
class Test6{
public static void main(String [] args){
DiffOfSquares d = new DiffOfSquares();
d.setRange();
}
}

Enjoy Coding !!!

Leave a Reply

Your email address will not be published. Required fields are marked *