Lua Implementation of Problem 6

View source code here on GitHub!

Solution

solution()
Returns:

The solution to problem 6

Return type:

number

 1-- Project Euler Problem 6
 2--
 3-- This turned out to be really easy
 4--
 5-- Problem:
 6--
 7-- The sum of the squares of the first ten natural numbers is,
 8-- 1**2 + 2**2 + ... + 10**2 = 385
 9--
10-- The square of the sum of the first ten natural numbers is,
11-- (1 + 2 + ... + 10)**2 = 55**2 = 3025
12--
13-- Hence the difference between the sum of the squares of the first ten natural
14-- numbers and the square of the sum is 3025 − 385 = 2640.
15--
16-- Find the difference between the sum of the squares of the first one hundred
17-- natural numbers and the square of the sum.
18
19return {
20    solution = function()
21        local sum = 1
22        local sum_of_squares = 1
23
24        for i = 2,100 do
25            sum = sum + i
26            sum_of_squares = sum_of_squares + (i * i)
27        end
28
29        return (sum * sum) - sum_of_squares;
30    end
31}

Tags: arithmetic-progression, sequence-summation