Given an n x n grid, count squares in it.
Input: n = 2 Output: 5 (4 squares of 1 unit + 1 square of 2 units) Input: n = 3 Output: 14 (9 squares of 1 unit + 4 square of 2 units + 1 square of 1 unit)
We strongly recommend you to minimize your browser and try this yourself first.
For a grid of size n*n the total number of squares formed are
1^2 + 2^2 + 3^2 + … + n^2 = n(n+1)(2n+1) / 6
Below is the implementation of above formula. Since the value of n*(n+1)*(2n+1) can cause overflow for large values of n, below are some interesting tricks used in the program.
1) long int is used in return.
2) n * (n + 1) / 2 is evaluated first as the value n*(n+1) will always be a multiple of 2.
Note that overflow may still happen, but above tricks just reduce chances of overflow.
Count of squares is 30
This article is contributed by Rishabh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Count squares with odd side length in Chessboard
- Program to count number of distinct Squares and Cubes upto N
- Minimum number of squares whose sum equals to given number n
- Find a point that lies inside exactly K given squares
- Check whether a number can be represented by sum of two squares
- Square pyramidal number (Sum of Squares)
- Count number of squares in a rectangle
- Paper Cut into Minimum Number of Squares
- Number of perfect squares between two given numbers
- Count number less than N which are product of perfect squares
- Number of squares of maximum area in a rectangle
- Number of unique rectangles formed using N unit squares
- Program to find the Nth Harmonic Number
- Program to find the Hidden Number
- Program to find the nth Kynea number