01 October 2012

Project Euler - Problem 6 (Java)

This time, I'm giving out the solution of Problem 6 in the form of Java code.

Without wasting more time, here's the code:

class euler6 {
public static void main (String [] args) {
int x = 0;
int y = 0;
for(int i=1;i<101;i++) {
x += i;
}

for(int j=1;j<101;j++) {
y += Math.pow(j, 2);
}

System.out.println("Square of the sum of the first one hundred natural numbers : " + Math.pow(x, 2));
System.out.println("Sum of the squares of the first one hundred natural numbers : " + y);
System.out.println("Hence, the difference of both numbers is " + Math.pow(x, 2) + " - " + y + " = " + (Math.pow(x, 2) - y));
}
}

And, here's a preview of its output.

As we can see, The answer doesn't match the one calculated in Visual Basic.
It is 2.516415E7.

What is E? E is a representation of exponential values. Let's take the answer above as an example.

We've got 2.516415E7, what does that mean? It actually means multiplying 2.516415 by E7(which is mathematically written as 10^7). Therefore, the answer could be written as :

 2.516415 x 10 ^ 7 

which equals to 25164150, the correct answer.

Search