Project Euler Problem 6
Onwards to…
The sum of the squares of the first ten natural numbers is,
12 + 22 + … + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025
385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
Bit of a disappointment, problem 6; it’s too easy. It’s rated as the third-easiest, i.e. easier than problems 3, 4, and 5 which I’ve already covered. In fact, for my money it’s easier than problem 2 as well. Ah well, the difficulty ramps up soon enough, trust me. Here’s the very simple python solution:
sum_sq = sum([ x*x for x in xrange(1, 101)]) sq_sum = sum(xrange(1, 101)) ** 2 print sq_sum - sum_sq
As you can see, it’s pretty intuitive. You sum the squares, square the sum, and calculate the difference. The answer is basically in the description, you just have to scale up a little.
There’s not much else to say about this one. Even if I abandon the functional approach and write a straightforward imperative solution it’s still very straightforward. In (deliberately non-idiomatic, so don’t whine at me) ruby:
sum_of_squares = 0 sum = 0 1.upto 100 do |x| sum_of_squares += x * x sum += x end p (sum * sum) - sum_of_squares
digg
del.icio.us
reddit
stumbleupon
August 14th, 2008 at 6:32 pm
This is actually not a really good general solution.
Rephrase the question to say “first 10^200 natural numbers”. Solve it using your method.
On the other hand, there are short formulas for the sum and the sum of squares, with number of terms that does not depend on n.
August 30th, 2008 at 3:07 pm
To continue with ASk’s line of thought:
The sum of the first n numbers is:
1 + 2 + 3 + … + n = n^2/2 + n/2
The sum of the squares of the first n numbers is:
1^2 + 2^ + 3^2 + … + n^2 = n^3/3 + n^2/2 + n/6
So another solution to the problem is:
(n^2/2 + n/2)^2 - (n^3/3 + n^2/2 + n/6)
or, simplified,
n^4/4 + n^3/6 - n^2/4 - n/6
October 22nd, 2008 at 10:52 pm
looking forward for more information about this. thanks for sharing. Eugene