Lua Implementation of Problem 28

View source code here on GitHub!

Includes

Solution

solution()
Returns:

The solution to problem 28

Return type:

number

 1-- Project Euler Problem 28
 2--
 3-- 1       ends at 1^2
 4-- 2-9     ends at 3^2
 5-- 10-25   ends at 5^2
 6-- 26-49   ends at 7^2
 7--
 8-- perimeter[0] = (1, )
 9-- perimeter[i] = ((2 * i - 1)^2, (2 * i + 1)^2]
10--
11-- .. code-block::
12--
13--     i = 1
14--     2 3 4 5 6 7 8 9
15--       ^   ^   ^   ^
16--     2i - 1, 2 * 2i - 1, 3 * 2i - 1, 4 * 2i - 1
17
18--     i = 2
19--     10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
20--           ^           ^           ^           ^
21--     2i - 1, 2 * 2i - 1, 3 * 2i - 1, 4 * 2i - 1
22
23--     i = 3
24--     26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
25--                     ^                 ^                 ^                 ^
26--
27-- the corners are:
28-- perimeter[i][x * 2i - 1 for x in (1, 2, 3, 4)]
29--
30-- Revision 1:
31--
32-- Extracted the code that finds the corners
33--
34-- Problem:
35--
36-- Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
37--
38-- 21 22 23 24 25
39-- 20  7  8  9 10
40-- 19  6  1  2 11
41-- 18  5  4  3 12
42-- 17 16 15 14 13
43--
44-- It can be verified that the sum of the numbers on the diagonals is 101.
45--
46-- What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
47
48local range_entry = loadlib("range").range_entry3
49
50return {
51    solution = function()
52        local answer = 1
53
54        for i = 1,(1000 / 2) do
55            local start = (2 * i - 1)^2 + 1
56            answer = answer + range_entry(start, 1, (1 * 2 * i - 1))
57            answer = answer + range_entry(start, 1, (2 * 2 * i - 1))
58            answer = answer + range_entry(start, 1, (3 * 2 * i - 1))
59            answer = answer + range_entry(start, 1, (4 * 2 * i - 1))
60        end
61
62        return answer
63    end
64}

Tags: grid-pattern