Java Program to Count Integral Points Inside a Triangle
public class Main
{
public static void main(String [] args)
{
Point p = new Point(0, 0);
Point q = new Point(25, 0);
Point r = new Point(0, 20);
int x = interiorPoint(p, q, r);
System.out.println("Number of total interior integral points " + x );
}
static int interiorPoint(Point p, Point q, Point r)
{
// total boundary points of 3 sides + 3 extra integral points for the vertices of triangle
int BoundaryPoints = boundaryPoint(p, q) + boundaryPoint(p, r) + boundaryPoint(q, r) + 3;
// Calculate 2 times of area of the triangle
int Area = Math.abs(p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y));
// Using Pick's theorem to calculate the no. of total Interior points
int i = (Area - BoundaryPoints + 2) / 2;
return i;
}
// Finds the no. of boundary integral points between 2 given points.
static int boundaryPoint(Point p, Point q)
{
// Check if line parallel to x-axes
if (p.x == q.x)
return Math.abs(p.y - q.y) - 1;
// Check if line parallel to x-axes
if (p.y == q.y)
return Math.abs(p.x - q.x) - 1;
int gcd = gcd(Math.abs(p.x - q.x),Math.abs(p.y - q.y)) - 1;
return gcd;
}
// GCD of 2 numbers
static int gcd(int p, int q)
{
int gcd = 1;
for (int i = 1; i<=p && i<=q; i++)
{
if(p%i==0 && q%i==0)
gcd = i;
}
return gcd;
}
}
class Point
{
int x, y;
public Point(int a, int b)
{
x = a;
y = b;
}
}
Output:
Number of total interior integral points 226
