So the other night I was a bit bored and decided to do something to pass the time. I first came across Project Euler a while ago, but had never gone further than problem #1. Boredom is a great motivator and I went through problems #2 thru #9 last night and I decided to post my solutions in search of better ones. Feel free to comment with your suggestions.
Project Euler’s Problem #6 statement is –
The sum of the squares of the first ten natural numbers is,
The square of the sum of the first ten natural numbers is,
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is
.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
Can’t be more straightforward than that, really.
sqr_sum = 0
num_sum = 0
for i in range(1,100 + 1):
num_sum += i
sqr_sum += i**2
num_sum = num_sum**2
print sqr_sum - num_sum
I’m pretty sure Niemeyer could rewrite this in one line, but whatever. This runs in 0.015s.


.