codelessgenie blog

Count Squares with Odd Side Length in Chessboard

Chessboard problems are classic in computer science and combinatorial mathematics. One such interesting problem is counting the number of squares of specific types in an n × n chessboard. This blog focuses on counting squares with odd side lengths. Understanding this problem requires combinatorial insights and careful mathematical formulation. We'll explore the problem in depth, derive a closed-form solution, discuss implementation best practices, and provide code examples.

2026-07

Table of Contents#

  1. Problem Statement
  2. Key Insight and Intuition
  3. Mathematical Formulation
  4. Deriving the Closed-Form Formula
  5. Proof of the Formula
  6. Implementation
    • Handling Integer Overflow
  7. Complexity Analysis
  8. Example Usage
  9. Common Pitfalls & Best Practices
  10. Conclusion
  11. References

1. Problem Statement#

Given an n × n chessboard, count all possible squares where the side length is an odd integer. For example:

  • n = 1: 1 square (side=1).
  • n = 2: 4 squares (all 1×1 squares).
  • n = 3: 10 squares (9 of 1×1 and 1 of 3×3).

2. Key Insight and Intuition#

  • Every square is defined by its top-left corner and side length k (where 1 ≤ k ≤ n and k is odd).
  • The number of possible top-left corners for a square of side k is (n - k + 1) × (n - k + 1).
  • Example: For n = 3, k = 1: 9 squares; k = 3: 1 square.

3. Mathematical Formulation#

The total number of squares with odd side lengths is the sum:
[ \text{T}(n) = \sum_{\substack{k=1 \ k \text{ odd}}}^{n} (n - k + 1)^2. ]


4. Deriving the Closed-Form Formula#

Rewrite k as k = 2i - 1 for i = 1, 2, \dots, m, where m = (n + 1) // 2 (the number of odd integers ≤ n).
[ \text{T}(n) = \sum_{i=1}^{m} (n - (2i - 1) + 1)^2 = \sum_{i=1}^{m} (n - 2i + 2)^2. ]
Through algebraic manipulation or combinatorial identities: [ \boxed{\text{T}(n) = \dfrac{n \times (n + 1) \times (n + 2)}{6}} ]


5. Proof of the Formula#

Proof by Test Cases:#

nCalculationResult
11×2×3/6 = 6/61
22×3×4/6 = 24/64
33×4×5/6 = 60/610
44×5×6/6 = 120/620

Combinatorial Proof:#

  • The formula counts all ways to place squares by decomposing the problem into the number of centers at integer coordinates (implicitly covering all odd-length squares).

6. Implementation#

The closed form is optimal, but integer overflow must be handled for large n (e.g., n ≥ 2.6e6 in 64-bit systems).

Key Approaches:#

  1. Direct Calculation with Early Division: Safe for n ≤ 2×10^6 in 64-bit systems by dividing early (e.g., (n * (n + 1) // 2) * (n + 2) // 3).
  2. Big Integers: For languages like Python or Java, use built-in arbitrary-precision integers.

Example Code (Python):#

def count_odd_squares(n: int) -> int:
    """
    Calculate the number of squares with odd side lengths in an n x n chessboard.
    
    Args:
        n: Side length of the chessboard.
    
    Returns:
        Count of squares with odd side lengths.
    """
    # Use integer arithmetic to avoid floating-point errors
    if n <= 0:
        return 0
    # Use 128-bit or big integers for n > 2×10^6 in lower-level languages.
    return n * (n + 1) * (n + 2) // 6
 
# Tests
print(count_odd_squares(3))  # Output: 10
print(count_odd_squares(4))  # Output: 20

Handling Overflow (C++ with __int128):#

#include <iostream>
using namespace std;
 
int main() {
    long long n;
    cin >> n;
    __int128_t a = n;
    __int128_t b = n+1;
    __int128_t c = n+2;
    __int128_t res = a * b * c / 6;
    // Output res (requires custom print for __int128)
    cout << static_cast<long long>(res) << endl; // Safe if res < LLONG_MAX
    return 0;
}

7. Complexity Analysis#

  • Time Complexity: O(1) with the closed form.
  • Space Complexity: O(1).
    Iterative solutions (which sum over odd k) run in O(n) time and are inefficient for large n.

8. Example Usage#

nSquares (1×1)Squares (3×3)TotalFormula (T(n))
11011
24044
3911010
41642020

9. Common Pitfalls & Best Practices#

  1. Pitfalls:

    • Integer overflow.
    • Not handling edge cases (n = 0).
    • Using iterative summation for large n.
  2. Best Practices:

    • Prefer closed-form solutions: Use T(n)=n*(n+1)*(n+2)/6.
    • Validate input: Ensure n is non-negative.
    • Test edge cases: n = 0, 1, 2, 10^9.
    • Use efficient arithmetic: Employ multiplicative decomposition or big integers.

10. Conclusion#

Counting squares with odd side lengths in a chessboard demonstrates the power of combinatorial mathematics. The closed form T(n)=n×(n+1)×(n+2)/6 provides an elegant, constant-time solution. While straightforward, implementation must handle potential integer overflow for large n. This problem is a great example of optimizing mathematical insights for efficient computation.


11. References#

  1. Combinatorial Mathematics Texts (e.g., Concrete Mathematics by Graham, Knuth, Patashnik).
  2. CSES Problem Set: Chessboard Puzzles.
  3. Integer Overflow Handling in Competitive Programming.