In this blog post we will be looking at problem 6 of Project Euler and we will program a solution in Java.
The problem of Project Euler found here, below is the problem for quick lookup.
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + … + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)^2 = 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.
-Project Euler Problem 6
Easy problem, So let’s start with breaking it into some smaller problems.
- We need to get a sum of all numbers from 1 to 100 and apply the power of 2 to that
- We need to get all numbers from 1 to 100 each to the power of 2 and sum these
The program starts by declaring two integer values each to 0 to hold the two values. After that we declare a for loop where we start the loop counter at 1. The loop continues as long as the loop counter is less than 101, so 1 till 100 inclusive. After every loop we add 1 to the loop counter.
Inside the for loop we add the loop counter(called natural number) to ‘squareOfEachSum’ after applying the power of 2 to it. On the next line we add the loop counter to the totalSum.
Once we have looped 100 times and exited the for loop we declare a new variable called ‘squareOfTotalSum’ where we save the ‘totalSum’ to the power of 2. We now have both values we need.
Then we use 3 print statements to show the output. The last one is the difference which is 25164150.
int squaresOfEachSum = 0;
int totalSum = 0;
for(int naturalNumber = 1; naturalNumber < 101; naturalNumber += 1){
squaresOfEachSum += Math.pow(naturalNumber, 2);
totalSum += naturalNumber;
}
int squareOfTotalSum = Math.pow(totalSum, 2);
System.out.println("Square of each sum: " + squaresOfEachSum);
System.out.println("Square of total sum: " + squareOfTotalSum);
System.out.println("Difference:" + (squareOfTotalSum - squaresOfEachSum));
Check out the ‘Project Euler in Java’ page for more solutions!
That was Project Euler problem 6 in Java!