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

1 Answer

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

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

import Foundation

// 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
}

let n = 3

// Validate input
guard n > 0 else {
    print("Grid size must be a positive integer!")
    exit(1) // Exit with error code
}

// Calculate and display the total number of squares
let totalSquares = countSquaresInNxNGrid(n)
print("The total number of squares in a \(n)x\(n) grid is: \(totalSquares)")



/*
run:

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

*/



 



answered Aug 31, 2025 by avibootz
...