Number of triangles

You are given a polygon of N sides with vertices numbered from 1, 2, ..., N. Now, exactly 2 vertices of the polygons are colored black and the remaining are colored white. You are required to find the number of triangles denoted by A such that:

  1. The triangle is formed by joining only the white-colored vertices of the polygon.
  2. The triangle shares at least one side with the polygon.

Example:

Input:  side=6, s1=2, s2=5
Output: 4

Approach

Java

public class NumberOftriangles {
    public static void main(String[] args) {

        long sides = 6;
        long s1 = 2;
        long s2 = 5;
        long x = s1 - s2;
        if (x < 0) {
            x *= -1;
        }
        x--;
        long y = sides - x - 2;
        long res = 0;
        if (x >= 3) {
            res += (x - 2);
            res += (x - 2) * (x - 3);
        }
        if (y >= 3) {
            res += (y - 2);
            res += (y - 2) * (y - 3);
        }

        if (x >= 2) {
            res += (x - 1) * y;
        }
        if (y >= 2) {
            res += (y - 1) * x;
        }

        System.out.println(res);

    }

    public static long sum(int n) {
        if (n % 2 == 0) {
            return (n / 2) * (n + 1);
        }
        return ((n + 1) / 2) * n;
    }

}


No comments:

Post a Comment