Tuesday, May 15, 2012

Project Euler, problem 28 solution

Problem 28

Somebody named... Euler wrote:
"First I noted that for an n by n grid, and n being odd, the number in the top right corner is n2.
A little mathematical analysis told me that the other corners are given by: n2-n+1, n2-2n+2, and n2-3n+3.
Adding these together gives the quadratic, 4n2-6n+6.
Then all I had to do was create a loop from 3 to 1001 in steps of 2 and find the running total
(starting from 1) of the quadratic."

JavaScript (Spider Monkey)

var s = 1;
for(var n = 3; n <= 1001; n += 2) {
    s += 4 * Math.pow(n,2) - 6 * n + 6;
}
print(s);
// time: 0.02s    memory: 4984 kB

Congratulations, the answer you gave to problem 28 is correct.
You are the 39019th person to have solved this problem.

No comments:

Post a Comment