This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
So I'm slowly making my way through Project Euler. I am currently on Problem 6. Having read that not all problems are solvable by brute force, I have begun by multiplying out (a+b+c+d+e+f+g+h+i+j)^10, giving me a^2 + b^2 + c^2 ...... + j^2 + 2ab + 2bc + 2ac + 2bd ..... + 2ij (do you see the pattern?). Then, if I do what the problem asks me to do and take away the sum of the squares of all the terms, I'm just left with the latter bit, all terms of which consist of 2 and a combination of two of the letters, e.g. "2bd" (there are 10C2 of those, aka 45). My plan is to get a loop to pair up those numbers in the combinations, putting * between them (making "2 * b * d"), put all of those into an array and return it, join the array items up into a long string, then chuck the whole thing into eval() and get my result. Before I even start writing my code, I want to ask - will that work? And does Java offer a better way of solving that problem?
Hey man, it's very easy. For the sum of squares, initiate a for loop till 100 and start by adding each number †Φ an already declared int variable. †ђξ number you'll be adding will be f †ђξ form pow(i,2). Let it all be in a named method. For †ђξ square f sums, add all †ђξ numbers till 100 then square it. Call it from †ђξ main method and subtract.
fred rosenberger wrote:Also...why are you computing anything to the 10th power? The problem states:
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
If that's the question, why are you computing anything at all? There's a closed-form expression for the sum of the squares of the integers from 1 to n, namely n(n+1)(2n+1)/6. Likewise there's a closed-form expression for the square of the sum of the integers from 1 to n, namely (n(n+1)/2) ^ 2. So the code is just a one-liner where you plug 100 in as the value of n.
Joined: Jun 16, 2012
Oh, silly me - I meant ^2, not ^10
Joined: Jun 16, 2012
Alright, I have the following:
Works perfectly for smaller numbers, however Project Euler tells me it's wrong when I try to do 100. Help please!
EDIT: whoops, never mind, I was just entering the answer wrongly. Thanks for the help!