Count squares with odd side length in Chessboard
Given a N * N chessboard, the task is to count the number of squares having the odd side length.
Example:
Input: N = 3
Output: 10
9 squares are possible whose sides are 1
and a single square with side = 3
9 + 1 = 10
Input: N = 8
Output: 120
Approach: For all odd numbers from 1 to N and then calculate the number of squares that can be formed having that odd side. For the ith side, the count of squares is equal to (N – i + 1)2. Further, add all such counts of squares.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int count_square( int n)
{
int count = 0;
for ( int i = 1; i <= n; i = i + 2) {
int k = n - i + 1;
count += (k * k);
}
return count;
}
int main()
{
int N = 8;
cout << count_square(N);
return 0;
}
|
Java
class GFG {
static int count_square( int n)
{
int count = 0 ;
for ( int i = 1 ; i <= n; i = i + 2 ) {
int k = n - i + 1 ;
count += (k * k);
}
return count;
}
public static void main(String[] args)
{
int N = 8 ;
System.out.println(count_square(N));
}
}
|
Python3
def count_square(n):
count = 0 ;
for i in range ( 1 , n + 1 , 2 ):
k = n - i + 1 ;
count + = (k * k);
return count;
N = 8 ;
print (count_square(N));
|
C#
using System;
class GFG {
static int count_square( int n)
{
int count = 0;
for ( int i = 1; i <= n; i = i + 2) {
int k = n - i + 1;
count += (k * k);
}
return count;
}
public static void Main()
{
int N = 8;
Console.WriteLine(count_square(N));
}
}
|
PHP
<?php
function count_square( $n )
{
$count = 0;
for ( $i = 1; $i <= $n ; $i = $i + 2)
{
$k = $n - $i + 1;
$count += ( $k * $k );
}
return $count ;
}
$N = 8;
echo count_square( $N );
?>
|
Javascript
<Script>
function count_square(n)
{
let count = 0;
for (let i = 1; i <= n; i = i + 2) {
let k = n - i + 1;
count += (k * k);
}
return count;
}
let N = 8;
document.write(count_square(N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
31 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...