Euler Problem 28


Finally got around to solving Problem 28 today in Java. It’s no where near as efficient as it could be but it got the problem done at least.

The size parameter it takes is the total number of elements in the spiral, so for the solution you would pass 1002001 to the program. (as 1001^2 equals 1002001)

Code is below:

// GPLv2
import java.util.ArrayList;

public class p28 {
    public static void main(String[] args) {
        int size = Integer.parseInt(args[0]);
        // 21 22 23 24 28
        // 20  7  8  9 10
        // 19  6  1  2 11
        // 18  5  4  3 12
        // 17 16 15 14 13

        // We start at one
        int next = 1;
        int tinc = 0;
        int incrementor = 2;
        int sum = 1;
        // we don't want to exceed our spiral size
        while (next < size) {
            if (next == 1) {
                next += 2;
                sum += next;
            } else {
                next += incrementor;
                sum +=next;
            }
            // increment times we have used incrementor
            tinc++;

            // our incrementer increases every 4th time
            if (tinc == 4) {
                incrementor +=2;
                tinc = 0;
            }
        }
        System.out.println("The total is " + sum);
    }
}

,

  1. No comments yet.
(will not be published)