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

2122 23 2425

2078910

19 612 11

1854312

1716 15 1413It 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?

I thought about this one for a couple days over a long weekend. Figured out a simplified algorithm. Wrote it in about 3 minutes. Runs in less than a second. Worked the first time.

import java.util.*;

public class Euler28

{

public static void main(String[] args)

{

System.out.print(“Problem 28:\n”);

Euler28 e = new Euler28();

System.out.print(“Answer = ” + e.Problem()+ “\n”);

}

public String Problem ()

{

ArrayList<Integer> S = new ArrayList<Integer>();

int limit = 500, c = 1, sum = 0;

S.add(c);

for (int i = 1; i <= limit; i++)

{

for (int k = 1; k <= 4; k++)

{

for (int j = 1; j <= 2*i; j++)

c++;

S.add(c);

}

}

for (int n: S)

sum += n;

return String.valueOf(sum);

}

}