10

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

 2 years ago
source link: http://siongui.github.io/2018/10/24/go-number-spiral-diagonals-problem-28-project-euler/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

October 24, 2018

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:

[2]Two-dimensional slices - Effective Go


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK