Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

What is the difference between the sum and square of a 100 numbers

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

2 Answers

In Swift, this could look like:

var squareOfSum = 0
var sumOfSquare = 0
var difference = 0

for var i = 1; i < 101; i++ {
    squareOfSum += i
    sumOfSquare += i * i
}

squareOfSum = squareOfSum * squareOfSum
difference = squareOfSum - sumOfSquare
println(difference)

I threw that together because I had a Playground open.

Translating that into Java shouldn't be too difficult - the concepts are precisely the same. Let me know if you struggle - I'll dig out the javac compiler and work it through.

Steve.

Hi Michael,

What's your question here? Is this one of the challenges?

If I was asked to write the code for this, I would start with a for loop to loop through 1 to 100. Inside the loop, I would add up each one cumulatively. This will be for the square of the sums. I would also cumulatively add together the square of each number - this will be the su of the squares.

Then, once the loop has finished, you can take the difference of the square of the sum and the sum of the square.

Hope that helps a little?

Steve.

It's problem 6 on project Euler

problem 6