JavaScript Program to Find Number of Squares in an N*N Grid
Last Updated :
24 Apr, 2024
Given a grid of side N * N, the task is to find the total number of squares that exist inside it.
Examples:
Input: N = 1
Output: 1
Input: N = 2
Output: 5
There are several approaches to finding the number of squares in an N*N grid which are as follows:
We can calculate the total number of squares in an N * N grid by calculating the number of squares without iterating through each possible square size. We use the formula to calculate the total number of squares in an N×N grid because it represents the sum of squares from 1 to n2.
Formula:
12 + 22 + ……… + n2 = n(n+1)(2n+1) / 6
We can prove this formula using induction.
We can easily see that the formula is true for
n = 1 and n = 2 as sums are 1 and 5 respectively.
Let it be true for n = k-1. So sum of k-1 numbers
is (k - 1) * k * (2 * k - 1)) / 6
In the following steps, we show that it is true
for k assuming that it is true for k-1.
Sum of k numbers = Sum of k-1 numbers + k2
= (k - 1) * k * (2 * k - 1) / 6 + k2
= ((k2 - k) * (2*k - 1) + 6k2)/6
= (2k3 - 2k2 - k2 + k + 6k2)/6
= (2k3 + 3k2 + k)/6
= k * (k + 1) * (2*k + 1) / 6
Example: Implementation of program to find Number of Squares in an N*N grid using direct formula
JavaScript
// Function to count squares
// using mathematical formula
function countSquaresMath(N) {
// Calculate the total number
// of squares using the formula
return (N * (N + 1) * (2 * N + 1)) / 6;
}
// Driver code
const N1 = 1;
const N2 = 2;
console.log(countSquaresMath(N1));
// Output: 1
console.log(countSquaresMath(N2));
// Output: 5
Time Complexity: O(1)
Auxiliary Space: O(1)
Iterative Counting
In this approach, we count the squares in the grid by iterating through each possible square size from 1 to N and counting the number of squares of that size.
Example: Implementation of program to find Number of Squares in an N*N grid using Iterative Counting
JavaScript
// Function to count squares
// using iterative counting
function countSquaresIterative(N) {
let totalSquares = 0;
// Iterate through each
// possible square size from 1 to N
for (let i = 1; i <= N; i++) {
// Add the number of squares
// of size i to the total count
totalSquares += i * i;
}
return totalSquares;
}
// Driver code
const N1 = 1;
const N2 = 10;
console.log(countSquaresIterative(N1));
// Output: 1
console.log(countSquaresIterative(N2));
// Output: 5
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...