Rust Implementation of Problem 28

View source code here on GitHub!

Includes

Problem Solution

pub fn problems::p0028::p0028() -> utils::Answer
 1/*
 2Project Euler Problem 28
 3
 41       ends at 1^2
 52-9     ends at 3^2
 610-25   ends at 5^2
 726-49   ends at 7^2
 8
 9perimeter[0] = (1, )
10perimeter[i] = ((2 * i - 1)^2, (2 * i + 1)^2]
11
12.. code-block::
13
14    i = 1
15    2 3 4 5 6 7 8 9
16      ^   ^   ^   ^
17    2i - 1, 2 * 2i - 1, 3 * 2i - 1, 4 * 2i - 1
18
19    i = 2
20    10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
21          ^           ^           ^           ^
22    2i - 1, 2 * 2i - 1, 3 * 2i - 1, 4 * 2i - 1
23
24    i = 3
25    26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
26                    ^                 ^                 ^                 ^
27
28the corners are:
29perimeter[i][x * 2i - 1 for x in (1, 2, 3, 4)]
30
31Revision 1:
32
33Extracted the code that finds the corners
34
35Problem:
36
37Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
38
3921 22 23 24 25
4020  7  8  9 10
4119  6  1  2 11
4218  5  4  3 12
4317 16 15 14 13
44
45It can be verified that the sum of the numbers on the diagonals is 101.
46
47What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
48*/
49use crate::include::ranges::range_entry3;
50use crate::include::utils::Answer;
51
52pub fn p0028() -> Answer {
53    let mut answer: u32 = 1;
54    for i in 1..(1002u32 / 2) {
55        let start = (2 * i - 1).pow(2) + 1;
56        answer += range_entry3(start, 1, 1 * 2 * i - 1) +
57                  range_entry3(start, 1, 2 * 2 * i - 1) +
58                  range_entry3(start, 1, 3 * 2 * i - 1) +
59                  range_entry3(start, 1, 4 * 2 * i - 1);
60    }
61    return Answer::Int(answer.into());
62}

Tags: grid-pattern