Euler 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?

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);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s