/*
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
fn count_squares_in_nxn_grid(n: i32) -> i32 {
// Formula: Total Squares = N * (N + 1) * (2N + 1) / 6
(n * (n + 1) * (2 * n + 1)) / 6
}
fn main() {
let n: i32 = 3;
// Validate input
if n <= 0 {
println!("Grid size must be a positive integer!");
std::process::exit(1); // Exit with error code
}
// Calculate and display the total number of squares
let total_squares = count_squares_in_nxn_grid(n);
println!(
"The total number of squares in a {}x{} grid is: {}",
n, n, total_squares
);
}
/*
run:
The total number of squares in a 3x3 grid is: 14
*/