/*
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?
*/
#include
#include
int spiral_diagonal_sum1 (int N)
{// Step through each corner number in the NxN spiral pattern, using the fact
// that the side length of each concentric box grows by 2.
int term = 1;
int diagonal_sum = 1;
int step = 2;
int i = 1;
while (step <= N - 1) {
term += step;
diagonal_sum += term;
i += 1;
if (i > 4) {
step += 2;
i = 1;
}
}
return diagonal_sum;
}
int spiral_diagonal_sum2 (int N)
{// In a box of side length n, the number in the upper-right corner is n^2 and
// the other corners are n^2 minus 1-, 2-, and 3-times n-1 (thanks, Mike!).
int diagonal_sum = 1;
for (int n = 3; n <= N; n += 2) {
diagonal_sum += 4 * pow (n, 2) - 6 * n + 6;
}
return diagonal_sum;
}
int main ()
{
int diagonal_sum;
diagonal_sum = spiral_diagonal_sum2 (1001);
std::cout << diagonal_sum << std::endl;
return 0;
}