JavaScript program to find Number of Squares in an N*N grid

A grid is a 2-dimensional arrangement of squares divided into rows and columns. From a given N*N square grid we have to calculate the total number of squares possible. There are multiple ways to find the number of squares in a given grid. In this article, we are going to learn about various approaches for calculating the number of squares in a given grid of size N*N.

Understanding the Problem

In an N×N grid, we can form squares of different sizes. For example, in a 4×4 grid, we can have:

  • 1×1 squares: 16 squares
  • 2×2 squares: 9 squares
  • 3×3 squares: 4 squares
  • 4×4 squares: 1 square
4×4 Grid Square Count 4×4 Grid 1×1 squares: 16 2×2 squares: 9 3×3 squares: 4 4×4 squares: 1 Total: 30 squares Formula: N(N+1)(2N+1)/6 For N=4: 4×5×9/6 = 30

Direct Formula

The mathematical formula for finding the total number of squares in an N×N grid is:

Total Number of Squares = (N * (N + 1) * (2N + 1)) / 6

Example

Input: N = 4
Output: 30

Calculation: (4 × 5 × 9) ÷ 6 = 180 ÷ 6 = 30

Method 1: Using Direct Formula

This is the most efficient approach using the mathematical formula directly.

function countSquaresFormula(n) {
    return (n * (n + 1) * (2 * n + 1)) / 6;
}

// Test with different grid sizes
let gridSizes = [3, 4, 5];

gridSizes.forEach(size => {
    let totalSquares = countSquaresFormula(size);
    console.log(`Grid ${size}×${size}: ${totalSquares} squares`);
});
Grid 3×3: 14 squares
Grid 4×4: 30 squares
Grid 5×5: 55 squares

Method 2: Using Loop Iteration

This approach iterates through all possible square sizes and counts squares for each size.

function countSquaresLoop(n) {
    let totalSquares = 0;
    
    // For each possible square size
    for (let size = 1; size <= n; size++) {
        // Count squares of current size
        let squaresOfCurrentSize = (n - size + 1) * (n - size + 1);
        totalSquares += squaresOfCurrentSize;
        
        console.log(`${size}×${size} squares: ${squaresOfCurrentSize}`);
    }
    
    return totalSquares;
}

let gridSize = 4;
let total = countSquaresLoop(gridSize);
console.log(`Total squares in ${gridSize}×${gridSize} grid: ${total}`);
1×1 squares: 16
2×2 squares: 9
3×3 squares: 4
4×4 squares: 1
Total squares in 4×4 grid: 30

Method 3: Using Recursion

This approach uses a recursive function to break down the problem into smaller subproblems.

function countSquaresRecursive(n) {
    // Base case
    if (n === 0) return 0;
    if (n === 1) return 1;
    
    // Recursive case: add squares of size n×n plus smaller grids
    return (n * n) + countSquaresRecursive(n - 1);
}

// Test the recursive approach
let gridSize = 4;
let totalSquares = countSquaresRecursive(gridSize);

console.log(`Using recursion for ${gridSize}×${gridSize} grid:`);
console.log(`Total squares: ${totalSquares}`);

// Show step-by-step breakdown
console.log("\nBreakdown:");
for (let i = 1; i <= gridSize; i++) {
    console.log(`Step ${i}: Adding ${i}×${i} = ${i*i} squares`);
}
Using recursion for 4×4 grid:
Total squares: 30

Breakdown:
Step 1: Adding 1×1 = 1 squares
Step 2: Adding 2×2 = 4 squares
Step 3: Adding 3×3 = 9 squares
Step 4: Adding 4×4 = 16 squares

Comparison of Approaches

Method Time Complexity Space Complexity Best For
Direct Formula O(1) O(1) Production code
Loop Iteration O(N) O(1) Understanding the logic
Recursion O(N) O(N) Educational purposes

Complete Example

// All three methods in one program
function demonstrateAllMethods(n) {
    console.log(`Finding squares in ${n}×${n} grid:<br>`);
    
    // Method 1: Formula
    let result1 = (n * (n + 1) * (2 * n + 1)) / 6;
    console.log(`Method 1 (Formula): ${result1}`);
    
    // Method 2: Loop
    let result2 = 0;
    for (let size = 1; size <= n; size++) {
        result2 += (n - size + 1) * (n - size + 1);
    }
    console.log(`Method 2 (Loop): ${result2}`);
    
    // Method 3: Recursion
    function recursive(num) {
        if (num === 0) return 0;
        return (num * num) + recursive(num - 1);
    }
    let result3 = recursive(n);
    console.log(`Method 3 (Recursion): ${result3}`);
    
    console.log(`\nAll methods give same result: ${result1 === result2 && result2 === result3}`);
}

demonstrateAllMethods(3);
Finding squares in 3×3 grid:

Method 1 (Formula): 14
Method 2 (Loop): 14
Method 3 (Recursion): 14

All methods give same result: true

Conclusion

The direct formula approach is most efficient for finding squares in an N×N grid with O(1) complexity. The loop and recursive methods help understand the underlying logic by breaking down the problem step by step.

Updated on: 2026-03-15T23:19:01+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements