RSS FEED

Project Euler: Problem 6

Problem No. 6 seems to be a quickie from the first sight:

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.

And indeed, there really is no catch hidden here, the only thing that needs to be done is to iterate over the range, add the numbers to the respective sums and after squaring one substract them. Okay, we can be smart and skip the first few entries since we've been already told the results for 1 to 10 – not that it would make any big difference, though, the execution time is tiny as is. In code it looks like this:
(
    local squareSum = 55
    local sumOfSquares = 385

    for i = 11 to 100 do
    (
        squareSum += i
        sumOfSquares += i^2
    )

    squareSum^2 - sumOfSquares
)

Hopefully the next problem will be more of a challenge.

DISCLAIMER: All scripts and snippets are provided as is under Creative Commons Zero (public domain, no restrictions) license. The author and this blog cannot be held liable for any loss caused as a result of inaccuracy or error within these web pages. Use at your own risk.

This Post needs Your Comment!

Return to top