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

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
'''

# Function to calculate the total number of squares in an N x N grid
def count_squares_in_nxn_grid(N):
    # Formula: Total Squares = N * (N + 1) * (2N + 1) / 6
    return (N * (N + 1) * (2 * N + 1)) // 6  # Integer division

def main():
    N = 3

    # Validate input
    if N <= 0:
        print("Grid size must be a positive integer!")
        return

    # Calculate and display the total number of squares
    total_squares = count_squares_in_nxn_grid(N)
    print(f"The total number of squares in a {N}x{N} grid is: {total_squares}")

if __name__ == "__main__":
    main()



"""
run:

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

"""

 



answered Aug 31 by avibootz
...