/*********************************************************************
Number spiral diagonals
Problem 28
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?
*********************************************************************/
/*********************************************************************
We begin by noticing immediately that the top right entry is always
n^2, where n is the length of the spiral. The top left entry must
therefore be (n-1) less than the top right, since there are n numbers
per side. This pattern is repeated in a counterclockwise direction
around the square. We summarize below:
top right: n^2
top left: n^2 - (n-1) = n^2- n+1
bottom left: n^2 -2(n-1) = n^2-2n+2
bottom right: n^2 -3(n-1) = n^2-3n+3
Summing up these diagonals yields: 4n^2 - 6n + 6
Therefore, we simply sum all the odd polynomials from n=3->1001
*********************************************************************/
#include
using namespace std;
int main()
{
const int max_n = 1001;
// Start at n = 3, and add in 1 (for n = 1 central 'square')
int sum = 1;
for (int n = 3; n <= max_n; n+=2)
sum += 4*n*n - 6*n + 6;
cout << sum << endl;
}
// >: 669171001