Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,959 questions

51,901 answers

573 users

How to find the number of squares in an N*N grid with Go

1 Answer

0 votes
package main

import (
    "fmt"
    "os"
)

/*
Total squares in a 3 * 3 grid are 14

1x1 squares = 9 Squares
2x2 squares = 4 Squares
3x3 squares = 1 Squares
*/

// Function to calculate the total number of squares in an N x N grid
func countSquaresInNxNGrid(N int) int {
    // Formula: Total Squares = N * (N + 1) * (2N + 1) / 6
    return (N * (N + 1) * (2*N + 1)) / 6
}

func main() {
    N := 3

    // Validate input
    if N <= 0 {
        fmt.Println("Grid size must be a positive integer!")
        os.Exit(1) // Exit with error code
    }

    // Calculate and display the total number of squares
    totalSquares := countSquaresInNxNGrid(N)
    fmt.Printf("The total number of squares in a %dx%d grid is: %d\n", N, N, totalSquares)
}



/*
run:

The total number of squares in a 3x3 grid is: 14

*/


 



answered Aug 31, 2025 by avibootz
...