Given a grid of side N * N, the task is to find the total number of squares that exist inside it. All squares selected can be of any length.
Examples:
Input: N = 1
Output: 1

Input: N = 2
Output: 5

Input: N = 4
Output: 30
Approach 1: Taking a few examples, it can be observed that for a grid on size N * N, the number of squares inside it will be 12 + 22 + 32 + … + N2
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cntSquares( int n)
{
int squares = 0;
for ( int i = 1; i <= n; i++) {
squares += pow (i, 2);
}
return squares;
}
int main()
{
int n = 4;
cout << cntSquares(4);
return 0;
}
|
Java
class GFG {
static int cntSquares( int n)
{
int squares = 0 ;
for ( int i = 1 ; i <= n; i++) {
squares += Math.pow(i, 2 );
}
return squares;
}
public static void main(String args[])
{
int n = 4 ;
System.out.print(cntSquares( 4 ));
}
}
|
Python3
def cntSquares(n) :
squares = 0 ;
for i in range ( 1 , n + 1 ) :
squares + = i * * 2 ;
return squares;
if __name__ = = "__main__" :
n = 4 ;
print (cntSquares( 4 ));
|
C#
using System;
class GFG
{
static int cntSquares( int n)
{
int squares = 0;
for ( int i = 1; i <= n; i++)
{
squares += ( int )Math.Pow(i, 2);
}
return squares;
}
public static void Main(String []args)
{
int n = 4;
Console.Write(cntSquares(n));
}
}
|
Javascript
<script>
function cntSquares(n)
{
let squares = 0;
for (let i = 1; i <= n; i++)
{
squares += Math.pow(i, 2);
}
return squares;
}
let n = 4;
document.write(cntSquares(n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach 2: By the use of direct formula.
However, the sum
has the closed form (direct formula)
. Hence, we can employ this to calculate the sum in
time.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int cnt_squares ( int n)
{
return n * (n + 1) * (2 * n + 1) / 6;
}
int main()
{
cout << cnt_squares (4) << endl;
return 0;
}
|
Java
class GFG {
static int cntSquares ( int n) {
return n * (n + 1 ) * ( 2 * n + 1 ) / 6 ;
}
public static void main(String args[]) {
System.out.println (cntSquares( 4 ));
}
}
|
Python3
def cntSquares(n) :
return int (n * (n + 1 ) * ( 2 * n + 1 ) / 6 )
if __name__ = = "__main__" :
print (cntSquares ( 4 ));
|
C#
using System;
class GFG
{
static int cntSquares ( int n)
{
return n * (n + 1) * (2 * n + 1) / 6;
}
public static void Main (String[] args)
{
Console.Write (cntSquares (4));
}
}
|
Javascript
<script>
function cntSquares (n)
{
return n * (n + 1) * (2 * n + 1) / 6;
}
document.write(cntSquares(4));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)