[Golang] Number spiral diagonals - Problem 28 - Project Euler


Problem: [1]

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?

Solution:

669171001

First take a look at the four numbers on the diagonals of N x N square. for example, 3 5 7 9 on 3 x 3 square. The difference is 2 on the numbers. So the difference is n-1 on N x N square. We use this observation to calculate all numbers on the diagonals and hence the sum of them.

Run Code on Go Playground

package main

import (
      "fmt"
)

func main() {
      sum := 1
      nextNumberInDiagoal := 1
      for j := 2; j < 1001; j += 2 {
              for i := 0; i < 4; i++ {
                      nextNumberInDiagoal += j
                      sum += nextNumberInDiagoal
                      //fmt.Println(nextNumberInDiagoal)
              }
      }
      fmt.Println(sum)
}

Test on:

References:

[1]Number spiral diagonals - Problem 28 - Project Euler
[2]Two-dimensional slices - Effective Go