Project-Euler-028

Problem

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

21 22 23 24 25
20  7  8  9 10
19  6  1  2 11
18  5  4  3 12
17 16 15 14 13

It can be verified that the sum of the numbers on the diagonals is 101.

What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?

Answer

1
669171001

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python
def sum_diagonals_of_spiral(size):
n = 1
step = 2
total = 0
since_last = 0
while n <= size**2:
total += n
n += step
since_last += 1
if since_last == 4:
step += 2
since_last = 0
return total

print(sum_diagonals_of_spiral(1001))

Ruby

1
2
3
4
5
6
7
8
9
#!/usr/bin/env ruby
i = 1
sum = i
step = 2
until i >= 1001**2
4.times { sum += i += step }
step += 2
end
puts sum

Haskell

1
2
main :: IO ()
main = print $ foldr (+) 1 [4*n^2 - 6*n + 6 | n <- [3,5..1001]]

Mathematica

1
2
3
4
5
6
7
8
9
10
11
(* 
* From the diagram, let's observe the four corners of an n * n square (where n is odd).
* It's not hard to convince yourself that the top right corner always has the value n^2.
* Working counterclockwise (backwards), the top left corner has the value n^2 - (n - 1),
* the bottom left corner has the value n^2 - 2(n - 1), and the bottom right is n^2 - 3(n - 1).
* Putting it all together, this outermost ring contributes 4n^2 - 6(n - 1) to the final sum.
*
* Incidentally, the closed form of this sum is (4m^3 + 3m^2 + 8m - 9) / 6, where m = size.
*)
size = 1001; (* Must be odd *)
Sum[Block[{n = 2k + 1}, 4 * n^2 - 6 * (n - 1)], {k, (size - 1) / 2}] + 1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public final class p028 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p028().run());
}


/*
* From the diagram, let's observe the four corners of an n * n square (where n is odd).
* It's not hard to convince yourself that the top right corner always has the value n^2.
* Working counterclockwise (backwards), the top left corner has the value n^2 - (n - 1),
* the bottom left corner has the value n^2 - 2(n - 1), and the bottom right is n^2 - 3(n - 1).
* Putting it all together, this outermost ring contributes 4n^2 - 6(n - 1) to the final sum.
*
* Incidentally, the closed form of this sum is (4m^3 + 3m^2 + 8m - 9) / 6, where m = size.
*/
private static final int SIZE = 1001; // Must be odd

public String run() {
long sum = 1; // Special case for size 1
for (int n = 3; n <= SIZE; n += 2)
sum += 4 * n * n - 6 * (n - 1);
return Long.toString(sum);
}

}
文章作者: Monad Kai
文章链接: onlookerliu.github.io/2018/04/12/Project-Euler-028/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Code@浮生记
支付宝打赏
微信打赏