Monday, April 30, 2012

Project Euler, Problem 6 solution

Problem 6

OK, just the code without any clarifications because no one reads my blog.

JavaScript (SpiderMonkey):

var n = 100;
var sqsum = (n * (n + 1) * (2 * n + 1)) / 6;
var sumsq = (1 + n) * n / 2;
print(sumsq*sumsq - sqsum);

('n' is here just for clarity of formula)

(time: 0.02s memory: 4984 kB on usual PC)

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

UPDATED:
krewllobster has also offered an interesting and fast option:

var a = 0, b = 0, x = 1;
while (x < 101) {
    a += Math.pow(x,2);
    b += x;
    x += 1;
}
print(Math.pow(b,2) - a);

(time: 0.01s memory: 4984 kB)

No comments:

Post a Comment