📌  相关文章
📜  通过将具有两个公共边和无公共边的 n 边多边形的顶点连接起来形成的三角形数

📅  最后修改于: 2021-10-23 08:16:16             🧑  作者: Mango

给定N边多边形,我们需要找到通过将给定多边形的顶点连接起来形成的三角形总数,其中两条边是公共的,没有边是公共的。
例子:

方法 :

  • 为了使三角形的两条边与多边形共用,我们将取 n 边多边形的任何一条边,取所选边的一个顶点并加入与另一个顶点的顶点相邻的边。
  • 遍历每个顶点并与另一个顶点的顶点相邻的边相邻,将有N个具有两个共同边的三角形。
  • 现在,要计算没有共同边的三角形的数量,从多边形中可能的三角形总数中减去具有一侧共同的三角形的总数和具有两侧的三角形的总数。
  • 没有公共边的三角形 = 三角形总数 ( n C 3 ) – 一侧公共三角形 ( n * ( n – 4 ) – 两侧公共三角形 ( n )。
  • 因此,与多边形没有公共边的三角形的数量将等于 n * ( n – 4 ) * ( n – 5 ) / 6。

注意:要计算一侧与多边形相同的三角形的数量,请单击此处
下面是上述方法的实现:

C++
// C++ program to implement
// the above problem
#include 
using namespace std;
 
// Function to find the number of triangles
void findTriangles(int n)
{
    int num = n;
 
    // print the number of triangles
    // having two side common
    cout << num << " ";
 
    // print the number of triangles
    // having no side common
    cout << num * (num - 4) * (num - 5) / 6;
}
 
// Driver code
int main()
{
    // initialize the number
    // of sides of a polygon
    int n;
    n = 6;
 
    findTriangles(n);
 
    return 0;
}


Java
// Java program to implement
// the above problem
import java.io.*;
 
class GFG
{
 
 
// Function to find the number of triangles
static void findTriangles(int n)
{
    int num = n;
 
    // print the number of triangles
    // having two side common
    System.out.print( num + " ");
 
    // print the number of triangles
    // having no side common
    System.out.print( num * (num - 4) * (num - 5) / 6);
}
 
// Driver code
public static void main (String[] args)
{
    // initialize the number
    // of sides of a polygon
    int n;
    n = 6;
 
    findTriangles(n);
}
}
 
// This code is contributed by anuj_67..


Python3
# Python3 program to implement
# the above problem
 
# Function to find the number of triangles
def findTriangles(n):
    num = n
     
 
    # print the number of triangles
    # having two side common
    print(num, end = " ")
 
    # print the number of triangles
    # having no side common
    print(num * (num - 4) * (num - 5) // 6)
 
# Driver code
 
# initialize the number
# of sides of a polygon
n = 6;
 
findTriangles(n)
 
# This code is contributed by Mohit Kumar


C#
// C# program to implement
// the above problem
using System;
 
class GFG
{
 
 
// Function to find the number of triangles
static void findTriangles(int n)
{
    int num = n;
 
    // print the number of triangles
    // having two side common
    Console.Write( num + " ");
 
    // print the number of triangles
    // having no side common
    Console.WriteLine( num * (num - 4) * (num - 5) / 6);
}
 
// Driver code
public static void Main ()
{
    // initialize the number
    // of sides of a polygon
    int n;
    n = 6;
 
    findTriangles(n);
}
}
 
// This code is contributed by anuj_67..


Javascript


输出:
6 2

时间复杂度: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程