// Solution to Project Euler problem 28
// Author: David J. Oftedal.
package main
import fmt "fmt"
// Sum up the diagonals in an n*n square spiral starting from 1.
func diagonals(n uint64) uint64 {
if n % 2 == 0 {
return 0
}
sum := uint64(1)
last := uint64(1) // Last number in the current row.
diff := uint64(0) // Difference between each corner and the next.
// Add up the four courners.
// Each row is 2 longer than the previous one.
for row := uint64(1); row < n; row+= 2 {
// The last number on each row is the square of the row's length.
last = row*row
// The difference between the corners increases by 2 as well.
diff += 2
// 4 corners + 1+2+3+4 * the difference between the corners.
sum = sum + 4*last + 10*diff
}
return sum
}
func main() {
// Calculate the sum of the diagonals in a 1001*1001 spiral.
fmt.Printf("The sum of the diagonals is %d.\n", diagonals(1001))
}