Count of integral coordinates that lies inside a Square
Last Updated :
24 May, 2022
Given lower left and upper right coordinates (x1, y1) and (x2, y2) of a square, the task is to count the number of integral coordinates that lies strictly inside the square.
Examples:
Input: x1 = 1, y1 = 1, x2 = 5, x3 = 5
Output: 9
Explanation:
Below is the square for the given coordinates:
Input: x1 = 1, y1 = 1, x2 = 4, x3 = 4
Output: 4
Approach: The difference between the x and y ordinates of the lower and upper right coordinates of the given squares gives the number integral points of x ordinates and y ordinates between opposite sides of square respectively. The total number of points that strictly lies inside the square is given by:
count = (x2 – x1 – 1) * (y2 – y1 – 1)
For Example:
In the above figure:
1. The total number of integral points inside base of the square is (x2 – x1 – 1).
2. The total number of integral points inside height of the square is (y2 – y1 – 1).
These (x2 – x1 – 1) integrals points parallel to the base of the square repeats (y2 – y1 – 1) number of times. Therefore the total number of integral points is given by (x2 – x1 – 1)*(y2 – y1 – 1).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countIntgralPoints( int x1, int y1,
int x2, int y2)
{
cout << (y2 - y1 - 1) * (x2 - x1 - 1);
}
int main()
{
int x1 = 1, y1 = 1;
int x2 = 4, y2 = 4;
countIntgralPoints(x1, y1, x2, y2);
return 0;
}
|
Java
class GFG {
static void countIntgralPoints( int x1, int y1,
int x2, int y2)
{
System.out.println((y2 - y1 - 1 ) *
(x2 - x1 - 1 ));
}
public static void main(String args[])
{
int x1 = 1 , y1 = 1 ;
int x2 = 4 , y2 = 4 ;
countIntgralPoints(x1, y1, x2, y2);
}
}
|
Python3
def countIntgralPoints(x1, y1, x2, y2):
print ((y2 - y1 - 1 ) * (x2 - x1 - 1 ))
if __name__ = = '__main__' :
x1 = 1
y1 = 1
x2 = 4
y2 = 4
countIntgralPoints(x1, y1, x2, y2)
|
C#
using System;
class GFG{
static void countIntgralPoints( int x1, int y1,
int x2, int y2)
{
Console.WriteLine((y2 - y1 - 1) *
(x2 - x1 - 1));
}
static void Main()
{
int x1 = 1, y1 = 1;
int x2 = 4, y2 = 4;
countIntgralPoints(x1, y1, x2, y2);
}
}
|
Javascript
<script>
function countIntgralPoints(x1, y1, x2, y2)
{
document.write( (y2 - y1 - 1) * (x2 - x1 - 1));
}
var x1 = 1, y1 = 1;
var x2 = 4, y2 = 4;
countIntgralPoints(x1, y1, x2, y2);
</script>
|
Time Complexity: O(1), as we are not using any loops.
Auxiliary Space: O(1), as we are not using any extra space.
Share your thoughts in the comments
Please Login to comment...