Problem 28 : Number spiral diagonals
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?
C++ source code
#include <iostream>
#include <cassert>
using namespace std;
class PE0028
{
public:
long int getSumOfNumbersOnSpiralDiagonals(int N);
};
long int PE0028::getSumOfNumbersOnSpiralDiagonals(int N)
{
// the law of the numbers:
//
// top right coner: (2n+1)^2
//
// top left corner: (2n+1)^2-(2n+1)+1
//
// lower left corner: (2n+1)^2-4*n
//
// lower right corner:(2n+1)^2-6*n
//
// 2n+1<=N : n<=(N-1)/2
int square;
long int sum = 1; // first number should be 1
for(int n=1; n<=(N-1)/2; n++)
{
square = (2*n+1)*(2*n+1);
sum += square; // top right coner
sum += square - (2*n+1) + 1; // top left corner
sum += square - 4*n; // lower left corner
sum += square - 6*n; // lower right corner
}
return sum;
}
int main()
{
PE0028 pe0028;
assert(101 == pe0028.getSumOfNumbersOnSpiralDiagonals(5));
cout << "The sum of the numbers on the diagonals in a 1001 by 1001 spiral ";
cout << "formed in the same way is " ;
cout << pe0028.getSumOfNumbersOnSpiralDiagonals(1001) << endl;
return 0;
Python source code
def getSumOfNumbersOnSpiralDiagonals(N):
"""
the law of the numbers:
top right coner : (2n+1)^2
top left corner : (2n+1)^2-(2n+1)+1
lower left corner : (2n+1)^2-4*n
lower right corner: (2n+1)^2-6*n
2n+1<=N : n<=(N-1)/2
"""
sum = 1 # first number should be 1
for n in range(1, int((N-1)/2.0)+1):
square = (2*n+1)*(2*n+1)
sum += square # top right coner
sum += square - (2*n+1) + 1 # top left corner
sum += square - 4*n; # lower left corner
sum += square - 6*n; # lower right corner
return sum
def main():
assert 101 == getSumOfNumbersOnSpiralDiagonals(5)
print("The sum of the numbers on the diagonals in a 1001 by 1001 spiral")
print("formed in the same way is",getSumOfNumbersOnSpiralDiagonals(1001))
if __name__ == '__main__':
main()