Stephen Tetreault
Stephen Tetreault

Reputation: 787

Project Euler #6 Java Assistance

This seems simple enough but I'm getting an incorrect answer output by my code. Can someone hint at what I'm possibly missing here, or what I possibly might've made a mistake on without giving away any solutions?

The problem is to find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

My code:

public class Main 
{
    public static void main(String[] args) 
{
        //Sum of Squares = (2n^3 + 3n^2 + n)/6
        //Square of Sums = ((n^2 + n)/2)^2

        double sum_squares = ((2*Math.pow(100,3) + 3*Math.pow(100, 2) + 100)/6);
        double square_sums =  Math.pow(((Math.pow(100, 2) + 100)/2), 2);
        System.out.println((square_sums-sum_squares)+"\n");
    }
}

My output is 2.516415E7 which is not correct, even when I enter it without scientific notation.

Dear Stack Overflow -- what presumably simple thing am I missing here!

EDIT: Peter de Rivaz solved my problem. What a silly mistake!

Upvotes: 0

Views: 532

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198143

The first thing that comes to mind is that you shouldn't be using doubles, but rather integer arithmetic.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340763

You must use exact, integer types like int, long or BigInteger. float/double will result in rounding errors. Besides - you are pretty close ;-).

Upvotes: 0

Related Questions