Fortran Implementation of Problem 28
View source code here on GitHub!
Includes
Problem Solution
- integer Problem0028/p0028()
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
48module Problem0028
49 use ranges
50 implicit none
51contains
52 pure integer function p0028() result(answer)
53 integer :: i, start
54
55 answer = 1
56 do i = 1, (1000 / 2)
57 start = (2 * i - 1)**2 + 1
58 answer = answer + range_entry3(start, 1, (1 * 2 * i - 1))
59 answer = answer + range_entry3(start, 1, (2 * 2 * i - 1))
60 answer = answer + range_entry3(start, 1, (3 * 2 * i - 1))
61 answer = answer + range_entry3(start, 1, (4 * 2 * i - 1))
62 end do
63 end function p0028
64end module Problem0028