Number of triangles formed by joining vertices of n-sided polygon with one side common
Last Updated :
20 Dec, 2022
Given N-sided polygon we need to find the number of triangles formed by joining the vertices of the given polygon with exactly one side being common.
Examples:
Input : 6
Output : 12
The image below is of a triangle forming inside a Hexagon by joining vertices as shown above. The two triangles formed has one side (AB) common with that of a polygon.It depicts that with one edge of a hexagon we can make two triangles with one side common. We can’t take C or F as our third vertex as it will make 2 sides common with the hexagon.
Triangle with one side common of a hexagon
No of triangles formed ie equal to 12 as there are 6 edges in a hexagon.
Input : 5
Output : 5
Approach :
- To make a triangle with one side common with a polygon the two vertices adjacent to the chosen common vertices cannot be considered as the third vertex of a triangle.
- First select any one edge from the polygon. Consider this edge to be the common edge. Number of ways to select an edge in a polygon would be equal to n.
- Now ,to form a triangle ,select any of the (n-4) vertices left .Two vertices of the common edge and two vertices adjacent to the common edge cannot be considered.
- Number of triangle formed by joining the vertices of an n-sided polygon with one side common would be equal to n * ( n – 4) .
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findTriangles( int n)
{
int num;
num = n * (n - 4);
cout << num;
}
int main()
{
int n;
n = 6;
findTriangles(n);
return 0;
}
|
Java
import java.io.*;
public class GFG
{
static void findTriangles( int n)
{
int num;
num = n * (n - 4 );
System.out.println(num);
}
public static void main(String [] args)
{
int n;
n = 6 ;
findTriangles(n);
}
}
|
Python3
def findTriangles(n):
num = n * (n - 4 )
print (num)
n = 6
findTriangles(n)
|
C#
using System;
class GFG
{
static void findTriangles( int n)
{
int num;
num = n * (n - 4);
Console.WriteLine(num);
}
public static void Main()
{
int n;
n = 6;
findTriangles(n);
}
}
|
Javascript
<script>
function findTriangles(n)
{
var num;
num = n * (n - 4);
document.write(num);
}
var n;
n = 6;
findTriangles(n);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...