Project Euler: Problem 28: Number Spiral Diagonals

Problem 28

Quite a simple implementation, I just noticed a pattern that the odd squares are multiples of 2 apart, so i added the corners (by subtracting the multiples of 2’s) to get the final result.



/**
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?
 */
import java.util.*;

public class problem28 {

	public static boolean perfect(double num){
		
		if(Math.sqrt(num) - Math.floor(Math.sqrt(num)) > 0)
			return false;
		else return true;
	}
    
    public static void main(String[] args) {
    	
		double sum = 1;
		int diag = 0;
		
		for(int i=2; i < 1001*1001+1; i++){
			if(perfect(i) && i % 2 != 0){
				diag += 2;
				sum += i + (i - diag) + (i - 2*diag) + (i - 3*diag);
			}
		}
	
	    System.out.println(sum);
    }
}



Output

——————–Configuration: ——————–
6.69171001E8

Process completed.

Previous Post

Leave a Reply