Count of squares that can be drawn without lifting the pencil
Last Updated :
07 Mar, 2022
Given an integer N, the task is to find the count of squares of side 1 that can be drawn without lifting the pencil, starting at one corner of an N * N grid and never visiting an edge twice.
Input: N = 2
Output: 2
Input: N = 3
Output: 5
Approach: It can be observed that for the values of N = 1, 2, 3, …, a series will be formed as 1, 2, 5, 10, 17, 26, 37, 50, … whose Nth term is (N2 – (2 * N) + 2)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSquares( int n)
{
return ( pow (n, 2) - (2 * n) + 2);
}
int main()
{
int n = 2;
cout << countSquares(n);
return 0;
}
|
Java
class GFG
{
static int countSquares( int n)
{
return ( int ) (Math.pow(n, 2 ) - ( 2 * n) + 2 );
}
public static void main(String []args)
{
int n = 2 ;
System.out.println(countSquares(n));
}
}
|
Python3
def countSquares(n) :
return ( pow (n, 2 ) - ( 2 * n) + 2 );
if __name__ = = "__main__" :
n = 2 ;
print (countSquares(n));
|
C#
using System;
class GFG
{
static int countSquares( int n)
{
return ( int ) (Math.Pow(n, 2) - (2 * n) + 2);
}
public static void Main(String []args)
{
int n = 2;
Console.WriteLine(countSquares(n));
}
}
|
Javascript
<script>
function countSquares(n)
{
return (Math.pow(n, 2) - (2 * n) + 2);
}
var n = 2;
document.write(countSquares(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...