给定 n > 3,找出 n 边凸多边形中的对角线数。
根据维基百科,在几何学中,对角线是连接多边形或多面体的两个顶点的线段,当这些顶点不在同一条边上时。非正式地,任何倾斜的线都称为对角线。
例子 :
Input : 5
Output : 5
说明:五个可能的对角线是:AC、AD、BD、BE、CE
解决方案 :
因为对于一个 n 边凸多边形,从每个顶点,我们可以绘制 n-3 条对角线,留下两个相邻的顶点和它自身。按照这种方式,对于 n 个顶点,将有 n*(n-3) 条对角线,但是我们将对每个对角线计算两次,因此对角线的总数变为 n*(n-3)/2
这是上述公式的代码。
C++
#include
using namespace std;
// C++ function to find number of diagonals
// in n sided convex polygon
int numberOfDiagonals(int n)
{
return n * (n - 3) / 2;
}
// driver code to test above function
int main()
{
int n = 5;
cout << n << " sided convex polygon have ";
cout << numberOfDiagonals(n) << " diagonals";
return 0;
}
Java
// Java function to find number of diagonals
// in n sided convex polygon
public class Diagonals {
static int numberOfDiagonals(int n)
{
return n * (n - 3) / 2;
}
// driver code to test above function
public static void main(String[] args)
{
int n = 5;
System.out.print(n + " sided convex polygon have ");
System.out.println(numberOfDiagonals(n) + " diagonals");
}
}
// This code is contributed by Saket Kumar
Python3
# Python3 program to find number of diagonals
# in n sided convex polygon
def numberOfDiagonals(n):
return n * (n - 3) / 2
# driver code to test above function
def main():
n = 5
print(n , " sided convex polygon have ")
print(numberOfDiagonals(n) , " diagonals")
if __name__ == '__main__':
main()
#this code contributed by 29AjayKumar
C#
// C# function to find number of diagonals
// in n sided convex polygon
using System;
class GFG {
static int numberOfDiagonals(int n)
{
return n * (n - 3) / 2;
}
// driver code to test above function
public static void Main()
{
int n = 5;
Console.Write(n + " sided convex polygon have ");
Console.WriteLine(numberOfDiagonals(n) +
" diagonals");
}
}
// This code is contributed by Sam007
PHP
Javascript
输出 :
5 sided convex polygon have 5 diagonals
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。